简体   繁体   中英

Chrome extension: Inject javascript into a webpage to perform a ajax request?

I'm developing a Google Chrome extension that adds a Windows Live Messenger-like notification when a user logs on Facebook and thus I need to perform a ajax request to grab some user information (like profile picture, full name from id etc.) So since I can't perform a ajax request to Facebook directly (Correct me if I'm wrong), is it possible to inject a Javascript file into the facebook page and then execute the ajax request from there? Or will this be blocked since the extensions run in another environment (Or do they? Once again correct me if I misunderstood this!) I don't have any code to show at the moment, but I was just wondering if it's possible before I start the coding or if I need some other way around this.

Thanks in advance

To inject it to head, you can write a function for it

function exec(fn) {
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')();';
    document.body.appendChild(script); // run the script
    document.body.removeChild(script); // clean up
}

and use it in your extension like

exec(function() {
    $("body").load('hacked.html');
});

taken from this answer

Chrome extensions are allowed to make ajax requests to any page. See docs for details.

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