5

I am using the chrome.tabs API to run a script every time a tab is updated. The script searches for a keyword in the page and if it finds it, it alerts you, but if it doesnt, it refreshes the page. Whenever I test the extension, the console tells me:

console error

manifest.json

{
  "name": "keyword checker",
  "version": "1.0.0",
  "manifest_version": 2,
  "background": {
      "persistent":true,
      "page":"background.html"
  },
  "icons": {
    "16": "icon-16.png",
    "128": "icon-128.png"
  },
  "page_action": {
      "default_icon": "icon-128.png"
  },
  "permissions": [
    "<all_urls>",
    "tabs"
  ]
}

background.html

<script src="jquery.js"></script>
<script src="background.js"></script>

background.js

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
  if(changeInfo && changeInfo.status == "complete"){
    chrome.tabs.executeScript(tabId, {file: "script.js"});
  }
});

script.js

if ($("div#wrap").is(":contains('comme')")) {
    alert('page contains keyword!');
  } else {
    window.location.reload(true);
  }
}

What am I doing wrong here? Any help is appreciated. I have included jquery in the root of the extension.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
user3376905
  • 177
  • 1
  • 3
  • 11

2 Answers2

11

You have only included jQuery on your background page. You should be injecting jQuery onto the tab you're executing script.js on.

Here is an example that loads jquery.js first, then in a callback loads script.js:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
    if(changeInfo && changeInfo.status == "complete"){
        chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function(){
            chrome.tabs.executeScript(tabId, {file: "script.js"});
        });
    }
});
nderscore
  • 4,182
  • 22
  • 29
  • Another question, how would include a jquery plugin in the background.js? Would it be the same principle? – user3376905 Mar 21 '14 at 01:16
  • 1
    @user3376905 Just load the plugin script after jquery in a callback the same way. – nderscore Mar 21 '14 at 02:41
  • Do I need to inject it every time I call `chrome.tabs.executeScript` or can I load it globally? I tried to include it into my `manifest.json`without success: `"js": ["content.js", "vendor/jquery-2.1.4.js"]` – Andi Giga Sep 21 '15 at 18:44
0

In my case, Issue was file path.

    {
    "name": "XYZ",
    "description" : "XYZ",
    "version": "1.0",
    "manifest_version": 3,
    "background": {
        "service_worker": "background.js"
    },
    "permissions": [
        "storage",
        "tabs"
    ],
    "action" : {
        "default_popup": "popup.html"
    },
    "content_scripts": [
        {
            "matches": ["*://*/*"],
            "js": ["./jquery.js", "./popup.js" ]
        } 
    ],
    "icons" : {
        "16": "/images/favicon-16x16.png",
        "32": "/images/favicon-32x32.png",
        "48": "/images/android-icon-48x48.png"
    }
}
Aman Gupta
  • 658
  • 1
  • 8
  • 14