Chrome 扩展:即使在 web_accessible_resources 中添加资源也不可用

Chrome Extension: Resource not available even adding it in web_accessible_resources

我正在使用 React/Redux 开发 Chrome 扩展。 为此,我正在使用 Webpack,现在我正在使用 WebPack DLLReference 插件将一些资源迁移到一个单独的文件,以优化构建过程。

然后我需要将生成的 dll/dll.vendor.js 加载到我的弹出窗口和注入的内容中。 对于 popup 它工作正常,但它不适用于注入的内容。

我已将其添加到清单中

"web_accessible_resources": [
    "dll/dll.vendor.js"
],

文件在那里,我什至可以使用路径访问它:chrome-extension:///dll/dll.vendor.js

但它不存在于注入的内容中,正如我在打开开发者工具 -> 源代码时看到的 当然,这会在以后产生丢失对象的错误。

迁移到 DLLReferencePlugin 之前一切正常。

我的 DLL webpack 配置文件:https://pastebin.com/z9RjRUqm

我的内容 webpack 配置文件:https://pastebin.com/0Niw2Fqm

The error I'm receiving

触发错误的行:

module.exports = vendor;

如果我检查弹出窗口,它有相同的行,如果我在那里设置断点并观察它定义的变量,问题只发生在内容中。

将我的扩展工具栏注入页面的代码: content/src/index.js

import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import {Store} from 'react-chrome-redux';

const anchor = document.createElement('div');
anchor.id = 'my-anchor';
document.body.appendChild(anchor)

const vendorUrl = chrome.runtime.getURL("dll/dll.vendor.js")

render(
  <Provider store={proxyStore}>
      <div>
          <script src={vendorUrl}></script>
          <link id='semantic-ui' rel='stylesheet' type='text/css'
                href='https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css' media='all' />
          <AppContainer>
              <ToolbarContent />
          </AppContainer>
      </div>
  </Provider>
  , document.getElementById('my-anchor'));

知道这个问题还有什么原因吗? 有没有更好的方法来调试为什么资源对内容环境不可用?

更新

根据我最后的发现,它的发生是因为依赖于 dll.vendor 的代码在页面上发生注入之前执行,但我不知道如何避免这种情况发生。

您对内容脚本的理解缺少一件事,Isolated World paradigm:

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

这有什么关系?好吧,如果您要将 <script> 元素添加到页面的 DOM,代码将在页面的上下文中执行,而不是在内容脚本的上下文中执行。这种技术称为 "page level" or "injected" scripts.

然而,这不是你想要的。您希望它在内容脚本上下文中,以便您可以使用这些库。然后你有选择:

  1. 如果您始终需要相同的脚本配置,最好将脚本作为数组添加到清单中。加载顺序很重要:

    "js" : [ "library.js", "actual_code.js" ]
    
  2. 如果您出于某种原因需要在运行时从现有内容脚本动态加载代码,您可以为您请求后台页面 inject it programmatically。如果您已经这样做了,只需按正确的顺序链接调用即可。

  3. 这不是技术上理想的解决方案,但您可以对您的内部资源进行 XHR,然后从内容脚本上下文中 eval()