javascript Chrome 扩展程序全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18840929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Chrome extension global variable
提问by user2786037
I've looked at other global variable questions on Chrome Extension with manifest ver 2, but found nothing.
我已经使用清单版本 2 查看了 Chrome 扩展程序上的其他全局变量问题,但一无所获。
Assume I have 2 files:
假设我有 2 个文件:
// content.js
var myVariable = myVariable(someDiv);
var myVarWithGlobe = VarWithGlobe.fromVariable(myVariable);
and
和
// VarWithGlobe.js
var withGlobe = withGlobe || { };
withGlobe.WithGlobe = (function(global) {
var myLocalVar = global.myVariable;
....
WithGlobe.fromVariable = WithGlobe;
both of them are added to web_accessible_resources, content_scriptsbut I can't access global.myVariable in second file since it is undefined.
它们都被添加到web_accessible_resources、content_scripts但我无法访问第二个文件中的 global.myVariable 因为它是未定义的。
How can I get it if I'm not allowed to change VarWithGlobe.js?
如果我不允许更改 VarWithGlobe.js,我该如何获得它?
回答by Andrey
Content scripts have own execution context (it is even different from the webpage context they are executing in). The only way is to pass messages to/from background page with variable. Check this answerfor code samples
内容脚本有自己的执行上下文(它甚至与它们正在执行的网页上下文不同)。唯一的方法是使用变量向/从后台页面传递消息。检查此答案以获取代码示例
回答by dw1
Include the file with the global first and it should be there.
首先包含全局文件,它应该在那里。
回答by Mela
In Chromium Version 35.0.1916.114 and probably in all the latest Chrome versions, it is possible to store global variables, while you're testing on the Chrome console.
在 Chromium 版本 35.0.1916.114 以及可能在所有最新的 Chrome 版本中,可以在 Chrome 控制台上进行测试时存储全局变量。
For example, if you use console.log()for a variable in your code, when you see it on your browser console, you can store it by right clicking on itand select "Store as Global Variable"
例如,如果您在代码中使用console.log()作为变量,当您在浏览器控制台上看到它时,您可以通过右键单击它并选择“存储为全局变量”来存储它
I Hope it can help you!
我希望它可以帮助你!