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.
2 Answers 2
an idea can be :
use
fetchapi to get a container that can be use to async load the script https://developer.mozilla.org/en-US/docs/Web/API/Fetch_APIuse
text()method which return a promise to get text contentfetch('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); });
2 Comments
fetch("some.json", {cache: "no-store"}) hacks.mozilla.org/2016/03/… 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.
type="text/plain". That way the script not executed, and you can get the text content to verify the version. Then you can create a new script element dynamically (with correct version details insrc) and load the script.