Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension - Uncaught ReferenceError: $ is not defined

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.

like image 601
user3376905 Avatar asked Dec 20 '22 16:12

user3376905


1 Answers

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"});
        });
    }
});
like image 65
nderscore Avatar answered Dec 22 '22 05:12

nderscore