我能够找到一种解决方法,也许是更好的解决方案。我现在使用 html5 api 来检测可见性状态。如果可见,我会向 backgroundPage 发送一条消息以显示 pageAction。这有效地替换了我用于显示 pageAction 的所有其他代码。
希望这会帮助其他人。
//contentScript.js
//This sections is to handle when we want to display the pageAction icon
function handleVisibilityChange(){
if (!document.webkitHidden){
//the page is now visible and is therefore not prerendering or in the background
chrome.extension.sendMessage({message: "pageLoaded", userLoggedIn: loggedIn()}, function(response) {
console.log(response.farewell);});
}
}
document.addEventListener("webkitvisibilitychange", handleVisibilityChange, false);
//Call the function incase the document is already visible/
handleVisibilityChange();
//backgroundPage.js
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse){
if (request.message == "pageLoaded"){
sendResponse({farewell: "goodbye"}); //close the connection.
console.log('detected page load');
if(request.userLoggedIn == true){
//Show regularPageAction
console.log('user logged in so showing pageaction normal');
chrome.pageAction.setPopup({tabId: sender.tab.id, popup: "popup.html"});
}
else{
//show non logged in page action.
console.log('user now logged in so showing pageaction non normal');
chrome.pageAction.setPopup({tabId: sender.tab.id, popup: "notLoggedIn.html"});
}
chrome.pageAction.show(sender.tab.id);
}
});