简体   繁体   English

我们可以在浏览器会话中跨网页引用 JavaScript 变量吗?

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

Going through w3schools tutorial for JavaScript, found below statement:通过w3schools的 JavaScript教程,发现以下语句:

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.例如,在 C 中,我们有 extern 关键字,使用它我们可以访问在另一个文件中声明的变量,但我们可以在我们的文件中引用它。

For example:例如:

Inside script tag of fileA.html, we have declared var x = 50 , outside function() declaration, so it is global wrt fileA.html.在 fileA.html 的 script 标签内,我们已经声明了var x = 50 ,在function()声明之外,所以它是全局wrt fileA.html。 If I have fileB.html, can we refer to x from within script tag embodied in fileB.html?如果我有 fileB.html,我们可以从包含在 fileB.html 中的 script 标签中引用 x 吗?

Just to be clear, this is not a scenario of reusing JavaScript files across webpages.需要明确的是,这不是跨网页重用 JavaScript 文件的场景。

You can use Web Workers ;你可以使用Web Workers MessageChannel , see How to clear the contents of an iFrame from another iFrame ; MessageChannel ,请参阅如何从另一个 iFrame 清除 iFrame 的内容 or window.postMessage() to communicate or pass variables between browsing contexts.window.postMessage()在浏览上下文之间进行通信或传递变量。


An approach utilizing SharedWorker一种利用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();
}

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.允许一个页面访问另一个页面的变量将是一个巨大的安全漏洞。

if your webpages are in the same DOMAIN, they could share a localStorage.如果您的网页在同一个域中,则它们可以共享一个 localStorage。 you can store strings in localStorage and load them on document ready.您可以将字符串存储在 localStorage 中并在准备好文档时加载它们。 You will need to handle concurrency/readwrite issues yourself however.但是,您需要自己处理并发/读写问题。

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.一旦脚本与除 cookie 之外的所有其他变量一起执行完毕,它们就会被销毁。

You can do what you are talking about (passing values in-between webpages) through cookies.您可以通过 cookie 执行您所说的操作(在网页之间传递值)。 They are stored on users computers and are not destroyed unless destroyed explicitly or are expired.它们存储在用户计算机上,除非明确销毁或过期,否则不会销毁。

You can use LocalStorage and Session Storage to achieve same.您可以使用 LocalStorage 和 Session Storage 来实现相同的目的。

MDN MDN

W3Schools W3学校

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.是的,这是一种“可能”,有一个概念调用ever cookie ,即使您从浏览器更改为浏览器,它也打算不惜一切代价保留 cookie,其想法是存储在浏览器中的任何可用存储机制中(本地存储) 、cookie、flash cookie、indexDB 等)数据。 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.因此,如果其中一个存储失败,cookie 会从一个位置复制到另一个位置,因此同时一个存储与 cookie 数据一起存在,这将始终存在。 Cross Browser support could works if the user have Flash Local Shared Object cookie如果用户有Flash Local Shared Object cookie则跨浏览器支持可以工作

the source: http://samy.pl/evercookie/来源: 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.说:我认为使用这种方法不是一个好主意,也许一个简单的localStorage['myvariable'] = {data:"data"}就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM