简体   繁体   English

在Chrome扩展程序中加载外部JavaScript

[英]Loading external javascript in a Chrome Extension

I'm trying to load some external javascript code in my Chrome extension. 我正在尝试在Chrome扩展程序中加载一些外部javascript代码。 However, due to the sandboxed environment of the extension, I can't see any of the functions defined by the external code. 但是,由于扩展的沙盒环境,我看不到外部代码定义的任何功能。

The external code implements a dependency mechanism, whereby one javascript file may require another, and so forth. 外部代码实现了一种依赖机制,其中一个javascript文件可能需要另一个,依此类推。 It also looks at arguments to the URL used to load the javascript to determine the top level javascript file to load. 它还查看用于加载javascript的URL的参数,以确定要加载的顶级javascript文件。 So it basically is able to load any arbitrary web app, and it is not known in advance all the files that will be used. 因此,它基本上可以加载任何任意Web应用程序,并且事先不知道将要使用的所有文件。 So I can't use any static definitions in the extension. 所以我不能在扩展中使用任何静态定义。

There is also the issue that since all extension code is sandboxed, I don't have complete access to the document - for instance, it can't access the window variable. 还有一个问题是,由于所有扩展代码都经过沙箱处理,因此我无法完全访问文档-例如,它无法访问window变量。

But if I put all the code in the external code, I run into content security problems if one script tries to load another. 但是,如果我将所有代码都放在外部代码中,那么如果一个脚本试图加载另一个脚本,则会遇到内容安全问题。 The whole reason I went was an extension is because of the bone-headed misimplementation of CSP by every single browser in existence whereby bookmarklets can't access external resources. 我去的全部原因是扩展,是因为现有的每个浏览器都对CSP实施了严重的误用,从而使书签无法访问外部资源。

What's the best practice for bypassing or working around the extension sandbox to basically be able to run code as if the page itself had loaded it, without any issues with CSP? 绕开或解决扩展沙箱以基本上能够像页面本身已加载代码一样运行代码,而CSP没有任何问题的最佳实践是什么?

In the content script you could do something like this to load the js file 在内容脚本中,您可以执行以下操作来加载js文件

function inject(url, exteral) {
    // 1. Build the absolute URL
    // 2. Create a script tag and set src attribute
    // 3. Append script tag to thw window
    if (!external){
       url = chrome.extension.getURL(url);
    }
    var scriptElement = document.createElement('script');
    scriptElement.src = url;
    (document.body || document.head || document.documentElement).appendChild(scriptElement);
}

If the js file is packged with the extension, it must be placed in the manifest.json under web_accesible_resources . 如果js文件与扩展packged,它必须被放置在manifest.jsonweb_accesible_resources othwerwise it need to have the same protocol that the page it is injected in (http | https) 否则,它需要具有与注入页面相同的协议(http | https)

Since the content script is not allowed to call the window functions, you could call window.postMessage to send data from the actual window to content script. 由于不允许内容脚本调用窗口函数,因此可以调用window.postMessage将数据从实际窗口发送到内容脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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