How to read javascript file in frontend javascript/browser - javascript

Please read carefully before marking as dupe.
I want to read a javascript file on frontend. The javascript file is obviously being used as a script on the webpage. I want to read that javascript file as text, and verify if correct version of it is being loaded in the browser. From different chunks of text in the js file, I can identify what version is actually being used in the end user's browser. The js file is main.js which is generated by angular build.
I know we can do something like creating a global variable for version or some mature version management. But currently, on production site, that will mean a new release, which is couple of months from now. Only option I have right now is html/js page, which can be directly served from production site, without waiting for new release.
So my question is, is it possible we can read a javascript file as text in hmtl/js code in the browser.

an idea can be :
use fetch api to get a container that can be use to async load the script
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
use text() method which return a promise to get text content
fetch('http://localhost:8100/scripts.js').then((res) => res.text()).then(scriptContent => {
// scriptContent contain the content of your script
// if (scriptContent.includes('version : 1.1.1')
console.log(scriptContent);
});

this is absolutely not an efficient way, but since you want to work without any new version release or working with a version management system
here is the thing
assume file's checksum (md5 sha125 or anything) of V1.0 equals X and you will calculate before the coding part.
if checksum(X) != X{
location.reload()
}
would help for a security features too since it's an important project.
another way of controlling this situation is changing the main.js file's name if it is possible.

Related

Make a small HTML application update a JSON file

I want to make a local HTML application read and update a JSON file and use its content to display HTML content. Alas, I'm stuck at the very first step, as I can't seem to setup any sort of test file that simply notices and reads a JSON file. From what I see online, I need to use other libraries. I attempted to use require.js but I can't make it work and the documentation doesn't help me.
I imported the require.js with a tag and attempt to launch something out of what I got from the documentation, but there's nothing to do. It doesn't look like it's willing to take .json files.
requirejs([
'example'
], function(example) {
const config = require('./config.json')
});
My issue is to get the program to read the file. From there I believe I can make the display of it, but this JS thing is all alien to me.
The recommended way would be to run a web server or use something like Electron and build a desktop app (as #chrisG points out in the comments). But if you wanna do this in the browser without an web server you could do something like:
Run Chrome with the --allow-file-access-from-files (or however you allow local file access in your browser of choice)
Put your JSON in a js file and load it (to just do this you don't need the flag, but if you want to use absolute path you'll need it)

Store HTML in browserDB using Node.js

I'm trying to store HTML files in the browser for an app built on NW.js or Electron.
Long story short: I want to make something like Sublime Text using a WYSIWYG editor (I don't know exactly how it works, so I will make a guess)
Creating a new TAB, all content inside the #editor is store in
localStorage/IndexedDB/NeDB/PounchDB/LimvoDB/... as the user is
writing.
When the user needs to save the file, it stores the content in the
browser window, and then it creates the file.
If the file already exists, the localStorage content overwrites it.
All the magic must happen around the browser DB.
You might be wondering why I'm not using files directly, and it's because the first request: We don't know if the user will save the file, but we don't want to lose all the content if the app is closed.
Searching the web, I find that is bad practice to pass HTML content through JSON, but I can't think of any other solution.. I'd have to use encodeURI and decode when retrieve the data to the #editor or the file saved.
I'm using:
Electron
Angular
I don't know yet what DB should I choose
Digging around, I also saw the sync function in PounchDB -> CouchDB and it blew my mind away ─it's a function to synchronize offline and online data using the named DB's.
Is it possible to store .HTML files in PounchDB and then synchronize it with CouchDB?
Is all this bad practice?
How would you do a Notepad - Sublime Text or a «MS Word» editor using PounchDB, or NeDB, or LimvoDB using Electron/NW.js engine?
Ended up using PouchDB, which also happen to handle very well html-strings.

How to locally fetch JSON without AJAX

I'm building a game using HTML5 Canvas and Javascript and I'm using JSON formatted tile maps for my levels. The tiles render correctly in FireFox, but when I use Chrome, the JSON fetching fails with a "Origin null is not allowed by Access-Control-Allow-Origin." I was using jQuery's $.ajax command and all my files are in one directory.
I would use this post's solution, but I can't use the web server solution.
Is there any other way to fetch JSON files to be parsed and read from? Something akin to loading an image just by giving the URL? Or is there some way to quickly convert my JSON files into globally available strings so I can parse it with JSON.parse()?
Why is the local web server not an option? Apache is free, can be installed on anything, and easy to use, IMO. Also, for Chrome specifically, look into --allow-file-access-from-files
But if nothing else works, maybe you could just add links to the files in script tags, and then append var SomeGlobalObject = ... to the top of each file. You might even be able to do this dynamically by using JS to append the script tag to head. But in the end, instead of using AJAX, you can just do JSON.parse(SomeGlobalObject)
In other words, load the files into the global namespace by adding script tags. Normally this would be considered bad practice, but used ONLY for testing, in the absence of any other options, it may work.
One option which may work for you in Chrome is to invoke the browser with the command line switch --allow-file-access-from-files. This question addresses the issue : Google Chrome --allow-file-access-from-files disabled for Chrome Beta 8
Another possibility is to fetch the JSON data as a script, setting a global variable to the JSON value

How to load file contents from another domain using just JS?

I'm thinking of doing some online file manipulation for mobile users, the idea being that the user provides a URL to the file, then the file contents are modified by the JS, and can then be downloaded. But I haven't been able to figure out how to get the file when it's on a separate domain using just JS.
Is this possible? If so any hints or examples would be appreciated.
Just wanted to add that part of what I wanted to do was make it available without my hosting it. I'm thinking of something like a a file they can host somewhere,and then all of the bandwidth is their own...and that of wherever they are getting the file from of course.
The only way to load contents of a file on another domain is from within a <script> tag. This is how JSONP works. Look into getting your target file into this format.
The other way would be to use a local proxy. Create a web service method that loads and returns the contents of the file, then call that locally using your favorite JavaScript framework.
Depending on how you think of public webservices, and within some limitations I'm still mapping, you can do this using an ajax call to YQL, like so.
(will expand the answer later).
http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20data.uri%20where%20url=%22http://t3.gstatic.com/images?q=tbn:ANd9GcSyART8OudfFJQ5oBplmhZ6HIIlougzPgwQ9qcgknK8_tivdW0EOg%22
One of the limitations of this method is file size, it currently tops out at 25k.

How do I stop js files being cached in IE?

I've created a page that uses the CKEditor javascript rich edit control.
It's a pretty neat control, especially seeing as it's free, but I'm having serious issues with the way it allows you to add templates.
To add a template you need to modify the templates js file in the CKEditor templates folder. The documentation page describing it is here.
This works fine until I want to update a template or add a new one (or anything else that requires me to modify the js file).
Internet Explorer caches the js file and doesn't pick up the update. Emptying the cache allows the update to be picked up, but this isn't an acceptable solution. Whenever I update a template I do not want to tell all of the users across the organisation to empty their IE cache. There must be a better way!
Is there a way to stop IE caching the js file? Or is there another solution to this problem?
Update
Ok, I found this section in the CKEditor API that will allow me to use the "insert timestamp into the url" solution suggested by several people.
So the script now looks like this:
config.templates_files =
[
'/editor_templates/site_default.js?time=' + utcTimeMilliseconds
];
Thanks for your help guys.
You can add rand seed to your js file. I mean <script src='jsFile.js?seed=12345'
And every time you want to empty cache - change seed number
Update:
as I understood you have to write like this config.templates_files = [ '/mytemplates.js?seed=12345' ];
Youo can add a timestamp query parameter when you include your .js file..
so instead of <script type="text/javascript" src="somefile.js"></script> you can <script type="text/javascript" src="somefile.js?timestampgoeshere"></script>
this should make the file to always get reloaded (the timestamp needs to be dynamic and changing for each load of the page..)
I am afraid you'll have to hack into the FCKEditor code and force the client JavaScript to load fresh copy of the XML file. You can do so by appending a ?random=<a random number> to the URL of the XML file being requested. FCKEditor is opensource so you should be able to locate the lines the request the XML and modify accordingly.
Set Expires-Header accordingly, e.g. in Apache
ExpiresActive On
ExpiresByType text/javascript access
This is not recommended for a real web application, only for intranet scenarios because the files will not be cachable.
every time you load the js file, pass a variable of a random number as a variable.
src='/libs/js/myfile.js?4859487594573
same trick for ajax loaded files.
Multiple methods (don't need to do them all):
press ^F5 (control + F5) - that'll load without cache
set pragma/cache headers on sending
use a random variable in the GET query string
.NET / C# :
public static void DisallowBrowserCache( )
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
}
You could make ASP.NET write a js file to the outputstream (http://server.com/jsFile.aspx, set http headers), and control the caching behavior of the response with the above method.

Categories