Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 336
Parth Narielwala Avatar asked Oct 20 '22 19:10

Parth Narielwala


1 Answers

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)'
        });
    }
});
like image 106
Kauê Gimenes Avatar answered Oct 27 '22 08:10

Kauê Gimenes