Chrome Extension: Communicating between Popup and Content Script

Tram Ho

1. Introduction

In the previous post Chrome Extension: Getting Started, I have introduced what chrome extension is and how to write a small but very useful chrome extension. In this post, we’re gonna up our game a little bit by writing a more complex chrome extension. The final extension will look like this:

This extension will help us to automatically send a certain message to a certain room of the Chatwork website. The full
source code can be found here: https://github.com/nguyenyou0812/auto-send-message

2. Key concepts

2.1. chrome.browserAction

Use browser actions to put icons in the main Google Chrome toolbar, to the right of the address bar. In addition to its icon, a browser action can have a tooltip, a badge, and a popup.

If a browser action has a popup, the popup appears when the user clicks the icon. The popup can contain any HTML contents that you like, and it’s automatically sized to fit its contents.

To add a popup to your browser action, create an HTML file with the popup’s contents. Specify the HTML file in the default_popup field of browser_action in the manifest, or call the browserAction.setPopup method.

2.2. Content Scripts

Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them and pass information to their parent extension.

Content scripts can access Chrome APIs used by their parent extension by exchanging messages with the extension. They can also access the URL of an extension’s file with chrome.runtime.getURL() and use the result the same as other URLs.

2.3. Chrome.tabs

Use the chrome.tabs API to interact with the browser’s tab system. You can use this API to create, modify, and rearrange tabs in the browser.

u can use most chrome.tabs methods and events without declaring any permissions in the extension’s manifest file. However, if you require access to the url, pendingUrl, title, or favIconUrl properties of tabs.Tab, you must declare the “tabs” permission in the manifest

3. Implementation

Creating a folder named AuSeMe and adding the following files. After that, loading this extension in chrome extension developer mode.

manifest.json

popup.html

popup.js

contentScript.js

4. Conclusion

In this post, I just showed you how to communicate between the popup and the content script by using Message Passing technique. Hopefully, this small tutorial will give you some ideas about how to connect the available chrome extension components and also inspire you to write many more big, power chrome extensions.

Share the news now

Source : Viblo