Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fetch a javascript file content and parse it to use it's variables

I am trying to fetch this javascript file

https://eloquentjavascript.net/code/journal.js

by using a native fetch command like

fetch('https://eloquentjavascript.net/code/journal.js').then(v => {
  //do something here
})

If the above journal.js is declaring a variable inside it - how can I use that variable in my current scope.

If I console.log(v) - then there is no way of accessing the variable - since chrome shows:

enter image description here

Is there any way to fetch a javascript file (as text) and then parse it so that we can use the imported file's objects and method in my current scope??

The content of this file declares a variable like:

var JOURNAL = [{"events":["carrot","exercise","weekend"],"squirrel":false},{"events":["bread","pudding","brushed teeth","weekend","touched tree"],"squirrel":false}]
like image 780
Probosckie Avatar asked Oct 23 '25 09:10

Probosckie


2 Answers

Use eval:

fetch('https://eloquentjavascript.net/code/journal.js').then(v => {
  v.text().then(txt => {
    eval(txt)
    console.log(JOURNAL)
  })
})
like image 72
Avraham Avatar answered Oct 26 '25 09:10

Avraham


You don't need to parse anything, you can also emulate the variables and functions the script requires and then let the browser evaluate the script.

// The script will try to access global in your current environnement
// So we define it and add it to our scope
let wrapped = window.global = {};

// Add the script to the page
$.getScript("https://eloquentjavascript.net/code/journal.js", function(){
  // wrapped now contains the wanted data !
  document.write(JSON.stringify(wrapped));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Alternative without jQuery:

function getScript(source, callback) {
    var script = document.createElement('script');
    var prior = document.getElementsByTagName('script')[0];
    script.async = 1;

    script.onload = script.onreadystatechange = function( _, isAbort ) {
        if(isAbort || !script.readyState || /loaded|complete/.test(script.readyState) ) {
            script.onload = script.onreadystatechange = null;
            script = undefined;

            if(!isAbort) { if(callback) callback(); }
        }
    };

    script.src = source;
    prior.parentNode.insertBefore(script, prior);
}
like image 30
Vinz243 Avatar answered Oct 26 '25 11:10

Vinz243



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!