简体   繁体   中英

Unable to use jquery in google chrome extension

I am trying to use jquery to make a post ajax call and I have tried almost all the solutions on SO but none seem to work. My manifest is:

{"name": "__MSG_extName__",
"version": "0.1",
"manifest_version": 2,
"description": "__MSG_extDesc__",
"icons": {"16": "icon16.png", "128": "icon128.png"},
"background": {"persistent": false, "scripts": ["background.js"]},
"default_locale": "en",
"content_scripts": [
{
  "matches": ["<all_urls>"],
  "js": ["jquery-2.1.3.js"]
}
],
"permissions": ["contextMenus", "downloads", "downloads.open", "tabs", "http://*/*", "https://*/*"]}

The background.js file is like:

chrome.downloads.onCreated.addListener(function(downloadItem) {

console.log("Download Link is " + downloadItem.url)
chrome.tabs.executeScript(null, { file: "jquery-2.1.3.js" }, function() {
console.log("jquery is loaded");
var linkSync = {
    "document": {
        "downloadLink": downloadItem.url,
        "isSynced": false},
    "safe": true
    };

$.post("url/to/post",
        linkSync,
        function( data ) {
        console.log("Success" + data );
    });
});

});

The error that I am getting is:

Download Link is http://www.mymp3song.com/files/download/id/33724
background.js:14 jquery is loaded
extensions::uncaught_exception_handler:8 Error in response to tabs.executeScript: ReferenceError: $ is not defined
at Object.callback (chrome-extension://kbhkaajolcelehoonafmkgaahfgphnok/background.js:22:2)
at chrome-extension://kbhkaajolcelehoonafmkgaahfgphnok/background.js:13:16

As you may see, I have added the jquery.js both programmatically and in the manifest but none seem to work. Even if I remove either of them it does not work. Can someone point to me what I should do to make it work?

If you want jQuery to function in your background page, you need to add it to the background page.

Both methods that you're trying to use are adding code to the content script context instead.

What you need is this:

"background": {
  "persistent": false,
  "scripts": ["jquery-2.1.3.js", "background.js"]
},

to load jQuery in your background page. Note that order matters.

I would recommend giving the Architecture Overview a look.

modify your your json to this and it will work for u reference is Here

"content_scripts": [ {
    "js": [ "jquery.min.js", "background.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM