Chrome Extension : make my extension to perform only when popup is clicked and display the results in the popup
As it clearly reads,
I want my popup to be the trigger for the extension to start.
My ext开发者_如何学Goension basically can be performed completely in background.html
. Background.html
needs some info from the webpage, so use message passing for passing the required content from contentscript.js
to background.html
. This is becoming resource heavy to run on all the pages, So i want this extension to start only after the icon is clicked and display the information in the popup.html
which i can directly pull from background.html
.
Lemme know if i'm unclear.
Detecting when a popup is opened is pretty easy as the code inside it executes each time the popup is opened. So all you need to do is put a request to background page at the beginning of popup code.
Second part would be injecting content script on demand (into the current tab as I understand).
So the whole extension structure should be something like this:
popup.html
//this will run each time popup opens
chrome.extension.sendRequest("start", function(data) {
//display data received from background page through content script
});
background.html
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request == "start") {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.executeScript(tab.id, {file: "contentscript.js"}, function() {
//content script is injected, send a request to it
chrome.tabs.sendRequest(tab.id, "get_data", function(data){
//content script sent response back with data we need to display in popup
sendResponse(data);
});
});
});
}
}));
Something to keep in mind is that the popup might be already closed by the time it receives the data, so you might need to add some error handling.
Second issue would be avoiding injecting content script twice into the same page. This might be challenging, so I would suggest if your content script is small then just inject it into all pages (in manifest).
精彩评论