chrome.tabs.onCreated and executescript for Chrome Extensions not working

寵の児 提交于 2019-12-12 15:42:36

问题


I'm trying to execute some script inside another external page off of a new tab listener.

background.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());
});

manifest.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"
  }
}

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

I want thealert('Hello World')to be injected into Yahoo!'s homepage (This is just an example of what I am trying to do in another extension)


回答1:


The problem with your code is becuase you added jQuery.js after the background.js file Here is the fix:

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

Another alternative for the executeScrit task:

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


来源:https://stackoverflow.com/questions/27850092/chrome-tabs-oncreated-and-executescript-for-chrome-extensions-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!