问题 Google Chrome中的“选项”页面和“背景”页面之间的通信


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

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

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


4349
2017-12-25 17:25


起源

一般来说,发布你的代码或者一个没有任何无关的演示问题的简化版本是个好主意。当人们看到代码时,更容易告诉他们出了什么问题。 - Brian Campbell


答案:


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

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

现在在您的选项页面中,您可以简单地使用 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>

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


16
2017-12-25 21:38





是的,那不会起作用:

<!--
  - JavaScript and HTML must be in separate files: see our Content Security
  - Policy  http://developer.chrome.com/extensions/contentSecurityPolicy.html
 -->

0
2017-10-15 06:41