Best practices for flashing Chrome extensions

I realized from the docs that closing chrome popup extensions when losing focus was the design choice.

I am working on an extension in which the user chooses to save items from a web page. When it interacts with the main web page, I would like the popup to be updated, but this is obviously not possible.

What is the right way to deal with this situation? (this is my first chrome extension)

+8
javascript google-chrome-extension
source share
2 answers

You may have a content script detect the save action. Suppose this is a specific DOM element that you know for sure, it will be in a specific master or created by yourself.

content.js

//content script document.onreadystatechange = function () { if (document.readyState == "complete") { // Grab the UI frmo the mainpage you want to append the save functionality var someElementsYouWantToAppendASaveButtonTo = document.getElementsByTagName("..."); var len = someElementsYouWantToAppendASaveButtonTo.length; for (var i = 0; i < len; i++) { // Create a UI save button to provide a functionality var theSaveButton = document.createElement("button"); theSaveButton.value = "Save to Chrome Extension"; // Send data to extension when clicked theSaveButton.addEventListener("click", function() { var dataToSentToExtension = {...} // Retrieve from the clicked element, or whatever you want to save chrome.extension.sendMessage(dataToSentToExtension, function(response) { if(response.success) console.log("Saved successfully"); else console.log("There was an error while saving") }); }, false); someElementsYouWantToAppendASaveButtonTo[i].appendChild(theSaveButton) } } } 

Then in the background you find the answer and customize the popup as you wish.

background.js

 chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { if(request.dataToSave) { chrome.storage.local.set(dataToSave, function() {...}); // You can then set upn the proper popup for the next click or even switch to it switch(request.popupToDisplay) { case "awesomeDisplay": chrome.browserAction.setPopup({...}) break; } var responseFromExtension = {success: true} } else { var responseFromExtension = {error: true} } }); 
+6
source share

It seems you want to change \ refresh the popup.html page according to the changes on the web page. If so, use content scripts and establish a connection for a separate message link to the background page (since focus is lost every time) and indirectly update popup.html .

Literature:

Link for the connection between popup and background page in addition to these, there are several questions on these topics, they will help you get started.

+1
source share

All Articles