Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

Loading external javascript in google chrome extension

I'm writing a Google Chrome extension which manipulates the current page (basically adds a button).

In my content script, I want to load the Facebook Graph API:

$fbDiv = $(document.createElement('div')).attr('id', 'fb-root');
$fbScript = $(document.createElement('script')).attr('src', 'https://connect.facebook.net/en_US/all.js');
$(body).append($fbDiv);
$(body).append($fbScript);

console.log("fbScript: " + typeof $fbScript.get(0));
console.log("fbScript parent: " + typeof $fbScript.parent().get(0));
console.log("find through body: " + typeof $(body).find($fbScript.get(0)).get(0));

However, the script doesn't seem to added to body. Here's the console log:

fbScript: object
fbScript parent: undefined
find through body: undefined

Any ideas on what I'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that the JavaScript inside the content scripts runs in its own sandboxed environment and only has access to other JavaScript that was loaded in one of two ways:

Via the manifest:

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "js": ["https://connect.facebook.net/en_US/all.js"]
    }
  ],
  ...
}

Or using Programmatic injection:

/* in background.html */
chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null,
                       {file:"https://connect.facebook.net/en_US/all.js"});
});

Be sure to update your manifest permissions:

/* in manifest.json */
"permissions": [
    "tabs", "https://connect.facebook.net"
 ], 

Appending a script tag will in effect evaluate the JavaScript in the context of the containing page, outside of the JavaScript sandbox that your JavaScript has access to.

Also, since the FB script requires the "fb-root" to be in the DOM, you will probably need to use the programmatic approach so that you can first update the DOM with the element, then pass a message back to the background page to load the Facebook script so it is accessible to the JavaScript that is loaded in the content scripts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...