简体   繁体   中英

How to execute my content script on a newly opened chrome tab?

I am calling a Chrome extension from a web portal to open a URL in a new tab, and on the newly opened tab I want to perform 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" });
  }
);

If I try to perform insertCSS and executeScript on extension click, it works fine

background.js

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

chrome.tabs.create doesn't return anything.

To make use of the created tab, you could wrap your method inside its callback, which has the created tab as a parameter:

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" });
    });
));

i solved my problem myself worked after giving active tabs permission to my extension 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" });
    });
  }
);

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"} );
    }
}

});

Description

'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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM