Channels ▼
RSS

Tools

Writing Chrome Extensions


Popup.html

Popup.html is basically a simple view that extracts data from background pages or content-scripts (which are JavaScript files) and displays them. Thus, it provides a way of displaying the results of the operations performed by the extension or the state of the extension.

In the manifest.json file, we describe which HTML file will act as the UI using the attribute popup. Note: There are many ways of displaying results to the user. We can use other HTML pages. The only difference is that we need to load those additional pages programmatically as needed, whereas with popup.html, we need not write any logic forloading because it is attached with one of the standard chrome event "browser action/page action" extensions — whenever we click the icon of the extension, popup.html will be displayed.

A sample popup.html is shown next, which just displays "Hello World" text when the extension icon is clicked, ( it extracts data from background.html):

<body>
  <h1>Hello World</h1>
  <script>
  var newwin = chrome.extension.getBackgroundPage();
  alert(newwin.val);//where val is a var declared in 
                     //the background page.
  </script>
</body>

The chrome.extension.getBackgroundPage() returns the window object of the background page from which we can access all the variables of background page that are in the window scope.

There is also an alternative way for the extensions pages to interact. They can use message passing as will be discussed in the section on content scripts.

Options.html

This file enables the user to customize the behavior of the extension. The options page should be included in the manifest.json file. It provides a link to the options page from the extensions management page at chrome://extensions. In the manifest.json file, you describe which file will be used as the options page using the attribute options_page.

Content Scripts

A content script is a JavaScript file that executes in the context of a Web page that's been loaded into the browser. Think of a content script as part of that loaded page, not as part of the extension it was packaged with. It interacts with the Web pages visited by the browser. It can also interact with the extension pages by exchanging messages (message passing). In the manifest.json file, you describe which file will be used as the content script using the composite attribute content_scripts. It consists of a child attribute named js that tells which file acts as the content script. The child attribute matches, which holds a regex-pattern/url-value, tells the extension on which domain names and URLs the content script is valid.

A sample of content script file is shown next, along with the message-passing method of interaction. It sends a request to the background.html page passing status=2 as data, and waits for response through the handler in which it displays the counter value from the response received.

var payload = {status: 2};
chrome.extension.sendRequest(payload, 
  function handler(response) {
      var a = response.counter;
      alert(a);
});

The background.html file shown next handles the above request sent by the content- script.

function onRequest(request, sender, sendResponse)
{
  var num1 = request.status;
  if (num1==2)
  {
      Num2=20;
      sendResponse({counter:Num2});
  }
}
//register this function
chrome.extension.onRequest.addListener(onRequest);

When the background page receives the request, it sends a response back if the value received is 2. In addition to the exchange of data with the background page, the content scripts can do much more by accessing the data of the loaded Web page, such as the document object and its properties, and also modify them as needed.

Chrome API

In addition to having access to all the APIs that Web pages and apps can use, extensions can also use Chrome-only APIs (often called chrome.* APIs) that allow tight integration with the browser. For example, any extension or Web app can use the standard window.open() method to open a URL. But if you want to specify which window that URL should be displayed in, your extension can use the Chrome-only chrome.tabs.create() method instead.

Content.js

Table 1 lists the supported chrome.* APIs.

bookmarks idle
browserAction management
contextMenus omnibox
cookies pageAction
extension proxy
fileBrowserHandler tabs
history types
i18n windows

Table 1.

Asynchronous vs. Synchronous Methods

Most of the methods in the chrome.* APIs are asynchronous: They return control back to the browser/script without waiting for the operation to finish and while the operation continues to happen in the background. To get the outcome of an operation after it is complete, a callback function is passed upfront to the method, which will be executed later (potentially much later), after the operation is complete. Here's an example of the signature for an asynchronous method:

chrome.tabs.create(object createProperties, 
  function callback)

Few chrome.* methods are synchronous. Synchronous methods will not have a callback because they don't return until they've completed all their work. Often, synchronous methods have a return type. For example:

DOMWindow chrome.extension.getBackgroundPage()

This method has no callback and a return type of DOMWindow — it synchronously returns the background page and performs no other asynchronous work.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video