【问题标题】:Communication between the Options page and Background Page in Google Chrome谷歌浏览器中选项页面和后台页面之间的通信
【发布时间】:2014-02-23 07:53:02
【问题描述】:

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

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

我错过了什么吗?还是我应该发布我的代码?

【问题讨论】:

  • 通常情况下,最好发布您的代码,或者发布一个能够演示问题的精简版本,而无需任何多余的东西。人们看到代码时更容易分辨出哪里出了问题。

标签: google-chrome


【解决方案1】:

在你的 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

【讨论】:

    【解决方案2】:

    是的,那是行不通的:

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

    【讨论】:

      猜你喜欢
      • 2011-01-25
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 2011-10-15
      • 2020-07-27
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      相关资源
      最近更新 更多