0

In the chrome console, I am able to execute the following javascript function found on another domain of mine:

(function() {
    var scr = document.createElement('script');
    scr.src = 'https://www.myawesomedomain.com/test.js';
    document.head.appendChild(scr);
    scr.onload = function(){ 
        myfunc(); 
    };
})()

Where test.js has the following code:

let myfunc = function() {
  alert ('you are awesome');
}

All good so far!

Now I have another file on the same domain called myjson.json with the following content:

{"message":"you are awesome!"}

and I would like to modify the initial code to extract the previous json value and do a console.log. I tried the following code, however it doesn't work for some reason:

(function() {
    var scr = document.createElement('script');
    scr.type = 'application/json';
    scr.src = 'https://www.myawesomedomain.com/myjson.json';
    document.head.appendChild(scr);
    scr.onload = function(){ 
        console.log(scr.message); 
    };
})()

this.QUESTION:

Am I doing something fundamentall wrong in the code above? I have been stuck here for a while sadly.

Webeng
  • 7,050
  • 4
  • 31
  • 59
  • Use an ajax or http call to resolve the json url more details here http://stackoverflow.com/questions/13515141/html-javascript-how-to-access-json-data-loaded-in-a-script-tag-with-src-set – Vinod Louis Apr 10 '17 at 05:19
  • **JSON is not Javascript.** (let that sink in, it is fundamental.) You cannot "execute" it by assigning it to a script tag. – Tomalak Apr 10 '17 at 05:20
  • @Tomalak thank you for the response! The json value is not stored in the scr in my sample code above? I'm sure I have something wrong in my understanding. I understood that since an inline script for instance can take a type value of "text/javascript" or "application/json" among others, that a script element created by `document.createElement` would also be viable. Or was it the execution that I miss understood? if the scr variable indeed has the json file stored in it, scr.message isn't the proper way to get the "you are awesome!" content? Sorry if these are noob/dummy questions. – Webeng Apr 10 '17 at 05:26
  • Thank you for the response @VinodLouis! The answer by Abhishek below includes the approach you were describing. I explained to him in a comment below that my main focus is understanding why my code isn't working as I expected it to. Would you happen to know what the error is in this instance? – Webeng Apr 10 '17 at 05:40
  • source includes an script file json cannod be loaded likewise you can find more details in the link i provided above – Vinod Louis Apr 10 '17 at 05:43
  • The script tag can take whatever type you care to give it. But it will only *execute* Javascript. And JSON is not Javascript. JSON is not a programming language at all. JSON is a data format, like CSV. Nothing more, nothing less. You would not try to execute CSV. Trying to execute JSON makes about as much sense. – Tomalak Apr 10 '17 at 05:43
  • Thank you @Tomalak. At which part of my code am I executing the scr variable? Is it on `scr.message`? I thought that if scr.message were just a file, that console.log would print it out appropriately, similar to how alert() works. Would you happen to know what I would need to replace in order to have it printed out? And thank you again for your detailed explanations. – Webeng Apr 10 '17 at 06:10
  • With CSV, you download the file with an Ajax request and then you use a CSV parser to turn it into an actual array which can be used by your code. With JSON, you download the file with an Ajax request and then you use a JSON parser to turn it into an actual array or object which can be used by your code. It's always the same procedure. – Tomalak Apr 10 '17 at 08:44

1 Answers1

0

You need to collect response inside your function, something like this, using ajax:

$.getJSON("https://www.myawesomedomain.com/myjson.json", function(result){
             console.log(result)
            });
        });

Collecting the result as a function argument is important.

Update

If you want to stick to your approach:

<script type="text/javascript">
        $(document).ready(function() {
        var scr = document.createElement('script');
        scr.type = 'application/json';
        scr.src = 'https://www.myawesomedomain.com/myjson.json';
        scr.onload = myFunction()
        document.head.appendChild(scr);
        })

        function myFunction() {
            console.log($(this).message)
        }
</script>

This seems to work. The reason why your code is not working is because you cannot embed a static call dynamically. In other words, you are embedding a script dynamically, then you need to have a predefined function, which onload will call. As i told in the comments, your onload was not getting called.

** update 2 **

While the above code with call the onload function, it may not achieve what you are trying to do. This is never possible as it opens a huge security hole.

Sources: Read response of a file called with script src tag from external sever

How to access plain text content retrieved via <script type="text/plain" src=...> in JavaScript?

Community
  • 1
  • 1
Abhishek Menon
  • 753
  • 4
  • 15
  • Thank you for the response Abhishek! For a few reasons, I do need to maintain the "nature" of the code that I am using above. My main issue is understanding why the previous code isn't working. I do still need to use the `document.createElement` part of the code for my purposes. Thank for trying to find an alternative for me with a different method :P, but I am interested in finding out why my previous code isn't working and hopefully adapting it. Would you happen to know why `console.log(scr.message);` isn't outputting anything? – Webeng Apr 10 '17 at 05:36
  • Webeng The issue is that document.createElement does not send a request to the src you have mentioned. In other words,.onload() is never getting executed. I have not seen the usage of DOM create element for this purpose. As the name suggests, it is used to create an element inside the page. If you really want to use your method, please try attaching the onload method to some other element. Please consider marking my answer correct if it helped you. Cheers! :) – Abhishek Menon Apr 10 '17 at 14:16
  • thank you for the response! The first portion of code I used does however work, and it uses the `scr.src` and `scr.onload` to do an asynchronous request (similar to how yours does). – Webeng Apr 10 '17 at 19:22
  • Updating my answer. Check it out. – Abhishek Menon Apr 10 '17 at 19:37