在Google Chrome扩展程序中加载外部JavaScript [英] Loading external javascript in google chrome extension

查看:171
本文介绍了在Google Chrome扩展程序中加载外部JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Google Chrome扩展程序来操作当前页面(基本上添加了一个按钮)。

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

在我的内容脚本中,我要加载Facebook图API:

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));

但是,脚本似乎没有添加到 body 。这是控制台日志:

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?

推荐答案

问题是内容脚本中的JavaScript在自己的沙盒环境中运行,只能访问以下两种方式之一加载的其他JavaScript:

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:

通过清单

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

或使用程序化注入

/* 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"
 ], 

附加脚本标签将有效地评估包含页面上下文中的JavaScript,在您的JavaScript可以访问的JavaScript沙盒之外。

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.

此外,由于FB脚本需要fb-root在DOM中,您可能需要使用编程方法,以便您可以先使用元素更新DOM,然后传递消息返回背景页面以加载Facebook脚本,以便内容脚本中加载的JavaScript可访问。

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.

这篇关于在Google Chrome扩展程序中加载外部JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆