Chrome扩展程序-注入脚本并在“非活动”标签上运行

时间:2019-10-21 20:19:01

标签: javascript google-chrome-extension

我有Chrome扩展程序,可在加载时将脚本插入页面。如果是某个页面,它将在该页面上的新选项卡中打开一组链接,并且在加载这些选项卡后,注入的脚本会在该选项卡上提交表单。问题是,注入不是在不是当前的选项卡上进行的。它仅在当前选项卡上起作用。

我的代码的简化版本:

manifest.json

{
  "name": "name",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "Doing stuff",
  "background": {
    "scripts": [
      "background.js"
    ],
    "persistent": true
  },
  "browser_action": {
    "default_title": "Bot"
  },
  "permissions": [
    "https://*.url.com/*",
    "*://*/*",
    "tabs"
  ]
}

background.js:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {


    if(changeInfo.status == 'complete') {

        try {
            chrome.tabs.executeScript(tab.ib, {
                file: 'inject.js'
            });

        } catch(err) {
            console.log(" extension cannot run on the chrome:// page ")
        }
    } 

})

inject.js:

(function() {

    function page1() {

        links = document.querySelectorAll("a.link_class");
        for(var link in links) {
            link.setAttribute("target", "_blank");
            link.click();
        }
    }

    function page2() {
        // this does not run in tabs that are inactive
        // in order to make it run, i have to click in the inactive tab and reload it manually
        document.querySelector("input[name='field_to_update']").text = "setting the field value";
        button = document.querySelector("input[name='button']");
        button.click();
    }

    if(document.querySelector("div.page1") != null) {
        page1();
    } else {
        page2();
    }
})();

0 个答案:

没有答案