Practical, straight-forward examples to aid the development of chrome extensions.
The aim of this blog post is to provide practical, straight-forward examples to aid the development of chrome extensions. This will be a live document, meaning I’ll update it frequently with meaningful examples I come across.
Communicate between background script and content script
Open website after extension is installed
In your background script background.js
:
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(
tabs[0].id,
{ msg: "example-send-to-content-script" },
(response) => {
if (response) {
console.log(response);
}
}
);
});
In your content script content.js
:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request && request.msg == "example-send-to-content-script") {
console.log("got message from background script!");
sendResponse({ sender: "content.js", data: ":thumbsup:" });
}
});
In your content script content.js
:
chrome.runtime.sendMessage({
message: "example-send-to-background-script",
});
In your background script background.js
:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "example-send-to-background-script") {
console.log("Message from content script!");
});
}
});
In your background script background.js
:
// This opens a page after extension is installed
chrome.runtime.onInstalled.addListener(function (object) {
chrome.tabs.create({ url: "https://mikesallese.me/" }, function (tab) {
console.log("Opening mikesallese.me after extension was installed!");
});
});