后台代码在任何弹出式单击时运行

Background code runs on any popup click

本文关键字:单击 运行 弹出式 任何 代码 后台      更新时间:2023-09-26

我正在尝试在后台页面中获取登录代码,以便在浏览器启动时仅运行一次。但似乎每次单击弹出窗口时,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();
}

简单的代码示例:

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://*/*"
  ]
}

弹出窗口.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();
在这种情况下,警报

被触发一次,当你加载扩展时,当你打开弹出窗口时,不会显示任何警报。问候。