1

Going through w3schools tutorial for JavaScript, found below statement:

A global variable has global scope: All scripts and functions on a web page can access it.

So, my query is, do we have a way to refer to variables declared in a particular webpage?

For example, in C, we have extern keyword, using which we can access the variables which are declared in another file, but we can refer to it in our file.

For example:

Inside script tag of fileA.html, we have declared var x = 50, outside function() declaration, so it is global w.r.t fileA.html. If I have fileB.html, can we refer to x from within script tag embodied in fileB.html?

Just to be clear, this is not a scenario of reusing JavaScript files across webpages.

Julian
  • 33,915
  • 22
  • 119
  • 174
a3.14_Infinity
  • 5,653
  • 7
  • 42
  • 66
  • JavaScript Global Variables are 'global' with respect to the containing global context (they are just properties of said context) - in the of a browser it is the Window object, which is distinct per each page-load and destroyed/recreated on each reload or navigation away. Each IFRAME will also establish it's own Window context, although there are some rules for reaching across. – user2864740 Mar 22 '16 at 05:20
  • 2
    Please wean yourself off w3schools as soon as you can, it's full of errors. – RobG Mar 22 '16 at 05:36
  • @RobG, I am heading to MDN tutorials -> https://developer.mozilla.org/en-US/docs/Web/JavaScript – a3.14_Infinity Mar 24 '16 at 03:59
  • @a3.14_Infinity See updated post; included an approach utilizing `SharedWorker` https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker – guest271314 Mar 24 '16 at 19:03

6 Answers6

3

You can use Web Workers ; MessageChannel , see How to clear the contents of an iFrame from another iFrame ; or window.postMessage() to communicate or pass variables between browsing contexts.


An approach utilizing SharedWorker

fileA.html

<!DOCTYPE html>
<html>
  <head>
    <script src="scriptA.js"></script>
  </head>
  <body>
    <a href="fileB.html" target="_blank">fileB</a>
  </body>
</html>

scriptA.js

var x = 50, p;

var worker = new SharedWorker("worker.js");

worker.port.addEventListener("message", function(e) {
  alert(e.data);
  if (!p) {
    p = document.createElement("p");
    p.innerHTML = e.data;
    document.body.appendChild(p)
  }
}, false);

worker.port.start();

console.log("Calling the worker from fileA")

worker.port.postMessage(x); // post `50` to worker

fileB.html

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="scriptB.js"></script>
  </head>
  <body>
  </body>
</html>

scriptB.js

var x, p;
var worker = new SharedWorker("worker.js");
worker.port.addEventListener("message", function(e) {  
  if (!x && !p) {
    x = e.data; // at `connections`:`1` : `e.data`:`50`
    p = document.createElement("p");
    p.innerHTML = "Message from fileA:" + x;
    document.body.appendChild(p)
  }
}, false);  
worker.port.start();  
console.log("Calling the worker from fileB");
worker.port.postMessage("");

worker.js

self.x = null, connections = 0;

onconnect = function(e) {
  var port = e.ports[0];
  ++connections;
  port.addEventListener("message", function(e) {
    if (!self.x) {
      self.x = e.data;
      port.postMessage("Received:" + self.x 
                       + " from fileA, total connections:" 
                       + connections);
    } else {
      port.postMessage("fileB received:" + self.x 
                       + " total connections:" 
                       + connections);
    }
  });
  port.start();
}
Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177
  • I believe those techniques only work across frame boundaries, not across navigation actions at the top level. – Tom Mar 22 '16 at 05:44
  • @Tom Given description of files at OP, if files are on same domain, should be able to pass `x` from `fileA.html` to `fileB.html` – guest271314 Mar 22 '16 at 06:00
  • 1
    @ guest271314 Only if the one page is framed by the other. It's not clear from the OP that there is a frame involved, and the linked W3C page doesn't suggest that either. If the idea is that the browser visits page1, then page2, and page2 wishes to access a global variable defined by page1, the answer is that it's impossible. The page1 script is no longer in memory, is not present in the JS interpreter. The only way to accomplish the task would be for page1 to marshall the data into a string and store it in a cookie or LocalStorage, _passing it forward explicitly_ before the page unloads. – Tom Mar 22 '16 at 06:24
  • @guest271314: Looks interesting. I tried running the example locally, but I am getting an error : Uncaught SecurityError: Failed to construct 'SharedWorker': (failure is happening in scriptB.js ) worker.js cannot be accessed from origin 'null'. Am I missing something? – a3.14_Infinity Mar 25 '16 at 05:01
  • @a3.14_Infinity Tried at both `file:` protocol and plnkr at chromium. Which browser are you triying `js` at ? – guest271314 Mar 25 '16 at 05:08
  • Google Chrome 49.0.2623.87 m – a3.14_Infinity Mar 25 '16 at 05:10
  • Not certain if this is issue, but you can try re-launching chrome with `--allow-file-access-from-files` flag set; see http://stackoverflow.com/questions/32996001/jquery-load-only-working-in-firefox/. You can navigate to `chrome://inpect/#workers` to view active `SharedWorker`s in browser – guest271314 Mar 25 '16 at 05:14
  • I tried again locally in my chrome, not working, but it is working in plunker. https://embed.plnkr.co/Ltfl4TUANho5rnJ7KktR/. Thanks !. Got to know about plunker. – a3.14_Infinity Mar 25 '16 at 05:32
0

lol No. ;)

When the browser navigates away from a page, the global scope and all scripts are completely unloaded before the next page is loaded.

Allowing one page to access another page's variables would be an enormous security hole.

Tom
  • 8,509
  • 7
  • 49
  • 78
  • So if i include Jquery in one page `Page1.html` and not include Jquery in `Page2.html` . Now i navigate from page1 to page2, will jquery can be used (or it has effect ) in page2? – Sandeep Mar 22 '16 at 05:19
  • @epascarello I tried with jqueryUI and bootstrap, both will affect the UI elements in Page2. Im very confused by this, Where can i get clarification? – Sandeep Mar 22 '16 at 05:25
  • I doubt jquery worked on page 2 if you did not include it. – epascarello Mar 22 '16 at 05:26
  • Why you lol? He is not making a joke he is asking a real question, why patronize an answer? – ncubica Mar 22 '16 at 05:30
0

if your webpages are in the same DOMAIN, they could share a localStorage. you can store strings in localStorage and load them on document ready. You will need to handle concurrency/readwrite issues yourself however.

0

By "global" they mean global throughout the particular script in which they are declared. They are destroyed as soon as the script finishes its execution along with all other variables except cookies.

You can do what you are talking about (passing values in-between webpages) through cookies. They are stored on users computers and are not destroyed unless destroyed explicitly or are expired.

Nijraj Gelani
  • 1,446
  • 18
  • 29
0

You can use LocalStorage and Session Storage to achieve same.

MDN

W3Schools

0

Yes is kind of "possible", there is a concept call ever cookie, which intent to persist at all cost a cookie even if you change from browser to browser,the idea is to store in any available storage mechanisms in the browser (local storage,cookie, flash cookie, indexDB, etc) the data. So if one of the storage fails, the cookie is copy from one location to another, so meanwhile one storage is alive with the cookie data, this will persist alway. Cross Browser support could works if the user have Flash Local Shared Object cookie

the source: http://samy.pl/evercookie/

Saying that: I don't think is a good idea use this approach, maybe whit a simple localStorage['myvariable'] = {data:"data"} could be sufficient.

ncubica
  • 8,169
  • 9
  • 54
  • 72