0

我试图在后台页面中获取登录代码,以便在浏览器启动时只运行一次。但似乎 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();
}
4

1 回答 1

0

简单的代码示例:

清单.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>

背景.js:

var someCustomType = new SomeCustomType();
function SomeCustomType() {
  this.firstProperty;
}
function thisShouldBeCalledOnce() {
  someCustomType.firstProperty = 'defined';
  alert('someCustomType.firstProperty=' + someCustomType.firstProperty);
  console.log('thisShouldBeCalledOnce');
}
thisShouldBeCalledOnce();

在这种情况下,警报被触发一次,当您加载扩展程序时,当您打开弹出窗口时不会显示任何警报。问候。

于 2012-05-16T19:21:22.810 回答