Google chrome extension 更改window.location.href后,executeScript是否仍然有效

Google chrome extension 更改window.location.href后,executeScript是否仍然有效,google-chrome-extension,Google Chrome Extension,当我更改window.location.href时,executeScript不起作用。这是为什么? manifest.json是 { "name": "Page Redder", "description": "Make the current page red", "version": "2.0", "permissions": [ "activeTab","*://*/*" ], "browser_action": { "default_title"

当我更改window.location.href时,executeScript不起作用。这是为什么? manifest.json是

{
  "name": "Page Redder",
  "description": "Make the current page red",
  "version": "2.0",
  "permissions": [
    "activeTab","*://*/*"
  ],
  "browser_action": {
    "default_title": "Make this page red"
  },
  "background": {
     "scripts": ["jquery-1.11.1.js","background.js"]
 },
  "manifest_version": 2
}
background.js是

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(tab.id,{code:'window.location.href="http://www.google.com"'},function(){
    chrome.tabs.executeScript(tab.id, {file:"test.js"}, function() {
    if (chrome.runtime.lastError) {
        console.error(chrome.runtime.lastError.message);
    }
    });
  }); 
});
test.js是

alert("hello work")

问题在于,第二个
executeScript
中的文件是在第一个
executeScript
的代码执行之后,但在
window.location.href
调用完成之前被注入的。请参见:在调用第二个
chrome.tabs.executeScript
的行上添加断点,单击浏览器操作,然后等待页面加载,然后再继续-弹出窗口将工作

解决这个问题的一种方法是添加一个
tabs.onUpdate
侦听器。然后,当您单击浏览器操作时,存储tabId是什么。如果更新的
tabId
与浏览器操作中设置的
tabId
匹配,则可以在
tabs.onUpdate
侦听器中执行
test.js
。快速示例:

var activeTabId;
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(tab.id, {code: 'window.location.href="http://www.google.com"'}, function (){
    activeTabId = tab.id;
  }); 
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if(tabId === activeTabId) {
    activeTabId = null; //To prevent executing the script multiple times
    chrome.tabs.executeScript(tabId, {file:"test.js"});
  }
});