如何在新打开的chrome选项卡上执行我的内容脚本?

时间:2016-07-06 08:48:39

标签: javascript google-chrome google-chrome-extension

我从网络门户呼叫Chrome扩展程序以在新标签页中打开网址,并在我要执行的新打开的标签页上executeScript

的manifest.json

"externally_connectable": {
  "matches": ["http://localhost:3000/*"]
},
"permissions": ["tabs", "http://*/*", "https://*/*"]

background.js

// listen to webportal
chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    a = chrome.tabs.create({ url: request.openUrlInEditor });
    chrome.tabs.insertCSS(a.id, { file: "combined.css" });
    chrome.tabs.executeScript(a.id, { file: "combined.js" });
  }
);

如果我尝试在扩展程序点击时执行insertCSSexecuteScript, 它工作正常

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.insertCSS(tab.id, { file: "combined.css" });
  chrome.tabs.executeScript(tab.id, { file: "combined.js" });
});

3 个答案:

答案 0 :(得分:1)

chrome.tabs.create不会返回任何内容。

要使用创建的选项卡,您可以将方法包装在其回调中,该回调将创建的选项卡作为参数:

chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
    chrome.tabs.create({ url: request.openUrlInEditor }, function(tab) {
        chrome.tabs.insertCSS(tab.id, { file: "combined.css" });
        chrome.tabs.executeScript(tab.id, { file: "combined.js" });
    });
));

答案 1 :(得分:1)

我自己解决了我的问题 在为我的扩展程序提供活动标签权限后工作 的的manifest.json

    "permissions": ["tabs", "http://*/*", "https://*/*","activeTab"]

<强> backround.js

// listen to webportal
chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    chrome.tabs.create({ url: request.openUrl },function(tab) {
        chrome.tabs.insertCSS(tab.id, { file: "combined.css" });
        chrome.tabs.executeScript(tab.id, { file: "combined.js" });
    });
  }
);

答案 2 :(得分:0)

Content.js

chrome.browserAction.onClicked.addListener(buttonClicked)
function buttonClicked(tab) {
   console.log("button clicked", tab)
   chrome.tabs.create({ url: LinkOfNewTab }, function(tab2) {
   console.log(tab2)
   extensionButtonClicked = true
})

}

Background.js

chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
if (extensionButtonClicked) {
    if (tab.url === Link1) {
        chrome.tabs.executeScript(tab.id, {file: "content.js"} );
    }

    if (tab.url === Link2) {
        chrome.tabs.executeScript(tab.id, {file: "content2.js"} );
    }
}

});

说明

'chrome.browserAction.onClicked' event will listen for icon when you click and 'chrome.tabs.create' will open up a new code and 'chrome.tabs.onUpdated' will fire every time when page reload or new tab is opened.