-2

Is it possible to pass a javascript-variable to a script on another site? I would like to do something like this:

This code is in a page on www.myfirstsite.net:

<script>
   var ID = 'randomstring';
</script>
<script src="http://www.mysecondesite.net/processingscript.js"></script>

How can I read the var ID in the script on mysecondsite.net?

Update: My question is wrong, as explained in the helpful answers from @vihan1086 and others.

Aiken
  • 272
  • 1
  • 8
  • You can't really do that perfectly. But in your other script, `ID` will already exist and you can just use it – Farzher Apr 25 '15 at 23:07
  • Have you tried your own proposed solution from your question? – boombox Apr 25 '15 at 23:07
  • Too bad. I've tried http://www.mysecondesite.net/processingscript.js#ID=randomstring but that doesn't seem to work and I can't find good info on the matter. Is it possible the solution is in that area? – Aiken Apr 25 '15 at 23:09
  • Yes, boombox, doesn't work. :( – Aiken Apr 25 '15 at 23:09

3 Answers3

1

In your other script, ID will already exist and you can just use it.

Farzher
  • 13,934
  • 21
  • 69
  • 100
1

Javascript runs in an environment attached to you web page, so as long a you dont change pages you can setup variable and includes other scripts that will have access to them.

So what you are proposing should work

However you should know that running script from other websites can be seen as dangerous and is therefore forbiden by some navigators/plugins ... so you should try and avoid it if possible (by providing a copy of the script on your website)

Amxx
  • 3,020
  • 2
  • 24
  • 45
1

Why to never do that

You should never declare variables like that, it has been described here

Then What?

On one page, do:

window.globals = {};
window.globals.my_variable = 'ABC';

On the script, add:

var globals = window.globals;
globals.my_variable;//Gets 'ABC'


This will keep all variables safe in a global place. Then we can get all global variables at once, increasing speed.

Don't forget to wrap all your code in something like:

(function() {

//Code here

})();

Functions

To make this easier I made functions:

setSharedVar (name, value) {
    if (!"globals" in window) {
        window.globals = {};
    }
    window.globals[name] = value;
}

getSharedVar (name) {
    if (!"globals" in window) {
        window.globals = {};
        return null;
    } else if (!name in window.globals) {
        return null;
    } else {
        return window.globals[name];
    }
}

Examples

Script 1:

setSharedVar('id', 5);

Script 2:

if (getSharedVar('id') === 5) {
    alert('Success!');
}

Alerts 'Success!'

Community
  • 1
  • 1
Downgoat
  • 13,771
  • 5
  • 46
  • 69