Google Chrome中的"选项"页面和"背景"页面之间的通信

Ult*_*nct 11 google-chrome

我正在尝试使用简单的Google Chrome扩展程序,我需要在选项页面和后台页面之间进行通信以获取/设置选项.

我尝试过chrome.extension.sendRequest(..)和chrome.extension.onRequest.addListener(..),但没有成功!

我错过了什么吗?或者我应该发布我的代码?

Moh*_*our 16

在你的background.html中,你可以有这样的东西:

<html>
<script>
  settings = {
    get foo() {
      return localStorage['foo'];
    },
    set foo(val) {
      localStorage['foo'] = val;
    }
  }
</script>
</html>
Run Code Online (Sandbox Code Playgroud)

现在,在您的选项页面中,您只需使用chrome.extensions.getBackgroundPage即可.例如在options.html中:

<html>
<head>
  <script>
  var bkg = chrome.extension.getBackgroundPage();
  function saveOptions() {
    bkg.settings.foo = 'bar';
  }
  function restoreOptions() {
    document.getElementById('foo').value = bkg.settings.foo;
  }
  </script>
</head>
<body onload="restoreOptions()"> 
  <form onsubmit="return false;">
    <input id="foo" type="text" />
    <button onclick="saveOptions();">Save</button>
  </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

记住一件事,开发指南是你最好的朋友:) http://developer.chrome.com/extensions/devguide