简体   繁体   中英

Injecting jQuery into Google.com using a Chrome Extension

I'm building a chrome extension and would quite like to inject jQuery into the Google website, but for some reason it just isn't working for me.

Here is my manifest file with the content_scripts :

"content_scripts": [{
    "matches": ["*://www.google.com/*"],
    "css": ["src/inject/inject.css"],
    "js": ["js/jquery/jquery.min.js", "src/inject/inject.js"],
    "run_at" : "document_start"
  }]

and jQuery is in the folder it is supposed to be. In my inject.js file I have:

$("body").append("Hello World");
console.log("Loaded.");

And strangely enough when I go to Google.com, Loaded. does appear in the console, but Hello World does not get appended to the body , nor do I get an error in the console which is very strange. I even did inside of inject.js :

if (window.jQuery) {  
    $("body").append("Hello World");
    console.log("Loaded.");
} else {
    console.log('Not Loaded.');
}

and Loaded. appeared in the console again, and Hello World did not get appened... I don't know what the problem is... It doesn't seem to make sense.

Any ideas? Thank you.

content scripts run in sandboxed contexts. So you cannot change the page-dom from within them. But there is a workaround:

in your content-script, you add all your scripts via script-tags like this:

var script_tag = document.createElement("script");
script_tag.setAttribute("src", chrome.extension.getURL("js/jquery/jquery.min.js"));

document.head.appendChild(script_tag);

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