Chrome 扩展的 chrome.tabs.onCreated 和执行脚本不起作用

2024-01-30

我正在尝试在新选项卡监听器的另一个外部页面内执行一些脚本。

背景.js

function onCreatedChrome(){
    chrome.tabs.onCreated.addListener(function(tab) {
        if (tab.url.indexOf("chrome-devtools://") == -1) {
            localStorage.setItem("tabid", tab.id);
            chrome.tabs.executeScript(tab.id, {code: "alert('Hello World')"}, function() {
                if (chrome.runtime.lastError) {
                    localStorage.setItem("Error", chrome.runtime.lastError.message);
                    console.error(chrome.runtime.lastError.message);
                }
                else{
                    localStorage.setItem("Else case", "This should work")
                }
            });
        }
    });
}


function createTab(){
    return function(){
        var url = "https://www.yahoo.com/";
        chrome.tabs.create({ url: url });
    }
}

$(document).ready(function(){
    onCreatedChrome();
    $("#button").click(createTab());
});

清单.json

{
  "manifest_version": 2,

  "name": "Execute Script",
  "description": "ExecuteScript extension",
  "version": "1.0",

  "permissions": [
    "activeTab",
    "tabs",
    "http://*/*",
    "https://www.yahoo.com/*"
  ],
  "content_scripts": [
    {
      "matches": ["https://*/*"],
      "js": ["jquery.js"]
    }
  ],
  "background":{
    "scripts": ["background.js", 
                "jquery.js"]
  },
  "browser_action": {
    "default_popup": "index.html"
  }
}

索引.html

<html>
    <head></head>
    <body>
        <button id="button">Click Me</button>
    </body>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="background.js"></script>
</html>

我想要alert('Hello World')被注入到 Yahoo! 的主页(这只是我在另一个扩展中尝试做的一个例子)


您的代码的问题是因为您添加了jQuery.js之后背景.js文件 这是修复方法:

"background":{
    "scripts": ["jquery.js",
                "background.js"]
  },

executeScrit 任务的另一种选择:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status != 'complete')
        return;
    if (tab.url.indexOf('yahoo.com') != -1) {
        chrome.tabs.executeScript(tabId, {
            code: 'alert(1)'
        });
    }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Chrome 扩展的 chrome.tabs.onCreated 和执行脚本不起作用 的相关文章

随机推荐