Can we refer to JavaScript variables across webpages in a browser session?

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="https://stackoverflow.com/questions/36146595/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="https://stackoverflow.com/questions/36146595/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();
}

Leave a Comment