如何在使用谷歌浏览器开发者控制台时使变量在标签页中可见

How to make a variable to be visible across tabs when using google chrome developer console

本文关键字:标签 变量 控制台 谷歌浏览器 开发者      更新时间:2023-09-26

我有一个脚本,通常在Chrome开发者控制台上打开的标签上执行。

我的一些变量对于所有选项卡都是通用的。

那么,如何使变量在选项卡中可见, 以便共享公共变量呢?

你可以

使用任何HTML5存储,我建议使用sessionStorage/localStorage。然后,在 sessionStorage/localStorage中更改的任何键都会为同一域中的所有选项卡触发Storage事件。

将处理程序添加到存储:

if (window.addEventListener) {
  window.addEventListener("storage", handle_storage, false);
} else {
  window.attachEvent("onstorage", handle_storage);
};

handle_storage,我们将倾听例如global_storage_vars关键来了解共享哪些变量。 Storage所有浏览器选项卡触发事件:

function handle_storage(e){
    e = e || window.event;
    //key that changed  e.key;
    //old value         e.oldValue;
    //new value         e.newValue;
    
    if (e && e.key === 'global_storage_vars') {
        console.log('The global vars changed to:', e.newValue);
        //here you can get a needed shared variable and do what you want
    }   
}

示例

第一个选项卡 - http://fiddle.jshell.net/r8dy8rf7/show/light/

第二个选项卡 - http://fiddle.jshell.net/nL7cq9xu/show/light/

在第一个选项卡控制台localStorage.setItem('global_storage_vars', {a : 1})中运行并检查第二个选项卡。

跨具有不同域的所有选项卡进行访问:

您可以制作Chrome扩展程序,它可以访问所有标签。