我正在尝试在后台页面中获取登录代码,以便在浏览器启动时仅运行一次。但似乎每次点击弹出窗口时,bgpage中的全局代码都会运行。它也在不同的范围内运行。有可能解决这个问题吗?
// background.js
var someCustomType = new SomeCustomType();
function SomeCustomType() {
this.firstProperty;
}
function thisShouldBeCalledOnce() {
someCustomType.firstProperty = 'defined';
alert('someCustomType.firstProperty=' + someCustomType.firstProperty);
console.log('thisShouldBeCalledOnce');
}
if (true) {
// Alwase 'undefined'
alert('someCustomType.firstProperty=' + someCustomType.firstProperty);
thisShouldBeCalledOnce();
}
答案 0 :(得分:0)
简单的代码示例:
<强>的manifest.json 强>
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
]
}
popup.html :只是一些虚拟代码:
<html>
<head>
</head>
<body>
<div>
<p> sometext</p>
<button type="button">Click Me</button>
</div>
</body>
</html>
<强> background.js:强>
var someCustomType = new SomeCustomType();
function SomeCustomType() {
this.firstProperty;
}
function thisShouldBeCalledOnce() {
someCustomType.firstProperty = 'defined';
alert('someCustomType.firstProperty=' + someCustomType.firstProperty);
console.log('thisShouldBeCalledOnce');
}
thisShouldBeCalledOnce();
在这种情况下,警报被触发一次,当您加载扩展时,当您打开弹出窗口时,将不会显示警报。问候。