0

バックグラウンド ページでログイン コードを取得して、ブラウザの起動時に 1 回だけ実行しようとしています。しかし、ポップアップがクリックされるたびに 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>

background.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 に答える