Skip to content

Instantly share code, notes, and snippets.

@dalgard
Last active April 20, 2020 13:02
Show Gist options
  • Save dalgard/7815269 to your computer and use it in GitHub Desktop.
Save dalgard/7815269 to your computer and use it in GitHub Desktop.
Inject content-script from browser-action and communicate with it
// Get the current active tab
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
// Send message to check whether the script has already been injected
chrome.tabs.sendMessage(tabs[0].id, "ping", function (response) {
// If no message handler exists (i.e. content-script hasn't been injected before),
// this callback is called right away with no arguments, so ...
if (typeof response === "undefined") {
// ... inject content-script (null means current active tab)
chrome.tabs.executeScript(null, { file: "content_script.js" });
}
//# Register events or other stuff that send messages to the content-script
});
});
// Listen for messages from browser-action or background script
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
var response;
// Message to check whether this script has been injected
if (request === "ping") {
// "Yeah, we're good"
response = "pong";
}
else {
//# Do whatever needs to be done
//# response = ...
}
sendResponse(response);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment