t31*_*321 5 javascript google-chrome google-chrome-devtools
我有一个脚本,我通常在Chrome 开发人员控制台上打开的选项卡中执行该脚本 。
我的一些变量对所有选项卡都是通用的。
那么如何使变量在选项卡中可见,以便我可以共享公共变量?
你可以使用任何HTML5存储,我推荐使用sessionStorage/ localStorage。然后,任何键在sessionStorage/中localStorage发生更改Storage都会触发同一域中所有选项卡的事件。
将处理程序添加到存储:
if (window.addEventListener) {
window.addEventListener("storage", handle_storage, false);
} else {
window.attachEvent("onstorage", handle_storage);
};
Run Code Online (Sandbox Code Playgroud)
在这里,handle_storage我们将监听例如global_storage_varskey 来了解共享哪些变量。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
}
}
Run Code Online (Sandbox Code Playgroud)
例子:
第一个选项卡 - http://fiddle.jshell.net/r8dy8rf7/show/light/
第二个选项卡 - http://fiddle.jshell.net/nL7cq9xu/show/light/
在第一个选项卡控制台中运行localStorage.setItem('global_storage_vars', {a : 1})并检查第二个选项卡。
您可以制作一个 Chrome 扩展程序,它可以访问所有选项卡。
| 归档时间: |
|
| 查看次数: |
1915 次 |
| 最近记录: |