我从文档中了解到,在失去焦点时关闭chrome扩展弹出窗口是一种设计选择。
我正在开发一个用户选择从网页中保存元素的扩展程序。当他与主网页交互时,我希望弹出窗口能够更新,但这显然是不可能的。
处理这种情况的正确方法是什么? (这是我的第一个chrome扩展名)
答案 0 :(得分:6)
您可以content script检测“保存”操作。让我们假设它是一个特定的DOM元素,你知道它肯定会出现在特定的main中,或者你自己创建的。
<强> 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)
}
}
}
然后,在后台,您可以检测到响应并根据需要设置弹出窗口。
<强> 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}
}
});
答案 1 :(得分:1)
您似乎希望根据网页中的更改修改\更新您的popup.html
页面。如果是,请使用内容脚本并为background page
connection建立communication popup.html
(因为焦点每次丢失)并间接更新popup
。
Reference用于background page
和{{1}}之间的通信,除此之外,
关于these主题有很多问题,它们会帮助你开始......