Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to object in background page from popup in Chrome extension

In a Chrome Extension I am developing, I want to access a data structure created and maintained in a background page when the popup is clicked. Unfortunately, I am new to Javascript and Chrome extension development in general, can you tell me how to do that? Does this involve message passing between the popup and the background page? Thanks.

like image 440
Raffo Avatar asked Jun 11 '12 20:06

Raffo


1 Answers

You can write three files like this to access a data structure in the background.html from your popup.html:


//in popup.html
<script type="text/javascript" src="mainscript.js"></script>
<!-- JavaScript and HTML must be in separate files for security. -->

//in mainscript.js
chrome.extension.getBackgroundPage().data = 'your data';

//in background.html
<script type="text/javascript">
var data;
</script>

and you need a manifest.json like this (maybe use browser_action instead of page_action):

....
,
"background_page": "background.html",
"page_action": {
    "default_icon": "your_icon.ico",
    "default_title": "Your title",
    "default_popup": "popup.html"
  },
....

edit: for message passing in chrome extensions see these functions

http://code.google.com/chrome/extensions/extension.html#method-sendRequest

http://code.google.com/chrome/extensions/extension.html#event-onRequest

and this useful description:

http://code.google.com/chrome/extensions/messaging.html

like image 124
user1434045 Avatar answered Sep 22 '22 16:09

user1434045