Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read javascript file in frontend javascript/browser

Tags:

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.

like image 778
Syed Aqeel Ashiq Avatar asked Oct 27 '25 03:10

Syed Aqeel Ashiq


1 Answers

an idea can be :

  1. 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

  2. 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);
    });
    
like image 167
jeremy-denis Avatar answered Oct 29 '25 18:10

jeremy-denis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!