Question

I'm attempting to write a Chrome Extension that places a small script on the target pages, then performs a specific action against items on the page. Being new to Chrome Extensions, I've started small with a "Hello World" alert. This works fine, however what I actually want to do involves using jQUery against the objects.

Although my target page already imports jQuery, if I attempt to use it in my script, I get an exception that $ is undefined. However, if I attempt to import it myself, even the alert stops working.

Below is my code, can anyone point out where I'm going wrong?

manifest.json

{
  "manifest_version": 2,

  "name": "Hello World",
  "description": "Simple Hello World Extension",
  "version": "1.0",

  "content_scripts": [
    {
      "matches": ["http://localhost:46950/"],
      "run_at": "document_end",
      "js": ["http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", "popup.js"]
    }
  ] 
}

popup.js

$(helloWorld());

function helloWorld()
{
    alert("Hello World");
}

Update

Digging into Chrome://extensions, I realised that when I attempt to use the code below, the extension isn't being loaded into Chrome at all. If I try to manually load it again, I get the below exception:

Could not load extension from ''. Could not load javascript '' for content script.

Was it helpful?

Solution

Ok, I managed to find this answer, which gave me some clues as to what was happening.

It appears that Chrome will not load in external resources in the extensions. Hence when I tried to load jQuery via google, it wouldn't load it, and crashed out the entire extension.

The reason I was trying to do this, was so as not to cause an issue where my multiple versions of the jquery conflicted between my extension and the target site. However, the answer indicates that the processes are essentially run in isolation, so it shouldn't have an issue. With that in mind, I've just added jquery into my extension manually and loaded it directly. this appears to work fine.

manifest.json

{
  "manifest_version": 2,

  "name": "Hello World",
  "description": "Simple Hello World Extension",
  "version": "1.0",

  "content_scripts": [
  {
      "matches": ["http://localhost:46950/"],
      "run_at": "document_end",
      "js": ["jquery-2.0.3.min.js", "popup.js"]
  }] 
}

OTHER TIPS

JQuery is expecting a dom element, so it is throwing an error.

It sounds like you are looking for something like $(document).ready(): http://learn.jquery.com/using-jquery-core/document-ready/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top