Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between the Options page and Background Page in Google Chrome

I am trying out a simple Google Chrome extension, in which I need to communicate between the options page and the background page for getting/setting the options.

I have tried chrome.extension.sendRequest(..) and chrome.extension.onRequest.addListener(..) but with no success!

Am I missing something? Or should I post my code?

like image 939
UltraInstinct Avatar asked Dec 25 '09 17:12

UltraInstinct


People also ask

How can background scripts and content scripts communicate?

Communication between extensions and their content scripts works by using message passing. Either side can listen for messages sent from the other end, and respond on the same channel.

What does Chrome do in the background?

Since Chrome is already running in the background, there is less that has to take place behind the scenes before your new browser window appears. This makes the browser feel quick, even on slower machines. Running in the background also allows any Chrome extensions you might have installed to continue to operate.

What is Chrome background page extension?

As the architecture overview explains, the background page is an HTML page that runs in the extension process. It exists for the lifetime of your extension, and only one instance of it at a time is active.


1 Answers

In you background.html, you could have something like this:

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

Now in your options page, you can simply use chrome.extensions.getBackgroundPage. For example in 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>

Remember one thing, the dev guide is your best friend :) http://developer.chrome.com/extensions/devguide

like image 92
Mohamed Mansour Avatar answered Sep 24 '22 11:09

Mohamed Mansour