Last active
April 20, 2020 13:02
-
-
Save dalgard/7815269 to your computer and use it in GitHub Desktop.
Inject content-script from browser-action and communicate with it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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