0

我正在使用React/Redux開發Chrome擴展程序。 爲此,我使用Webpack,現在我正在使用WebPack DLLReference插件將一些資源遷移到分離的文件中,以優化構建過程。Chrome擴展程序:即使將其添加到web_accessible_resources中,資源也不可用

然後我需要將生成的dll/dll.vendor.js加載到彈出窗口和注入內容中。 對於彈出它工作正常,但它不適用於注入的內容。

我已經把它添加到清單

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

該文件是存在的,我甚至可以使用路徑訪問它:鉻擴展:///dll/dll.vendor.js

但是它並沒有出現在注入的內容中,因爲我可以看到打開開發工具 - >來源 這當然會在以後生成丟失對象的錯誤。

在遷移到DLLReferencePlugin之前,一切正常。

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

我的內容的WebPack配置文件:https://pastebin.com/0Niw2Fqm

The error I'm receiving

觸發錯誤行:如果我檢查彈出

module.exports = vendor; 

,它具有相同的行,如果我在那裏設置一個斷點並且觀察它定義的變量,問題就會出現y發生在內容中。

注入我的推廣工具欄到頁面的代碼: 內容/ 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')); 

任何想法,還有什麼可能是這個問題的原因是什麼? 任何更好的方法來調試爲什麼資源不可用於內容環境?

UPDATE

根據我的,因爲這取決於dll.vendor代碼注入發生在頁面上之前執行,但我不知道我怎樣才能避免這種情況發生它發生最後的調查結果。

+0

那怎麼注入的內容?它從你的問題中缺失。 – Xan

+0

通過渲染 danielfranca

+0

但不管怎樣,它至少應在源文件中列出的,對不對? – danielfranca

回答

1

有一件事情從您的內容腳本的理解缺失,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()

+0

感謝您的詳細解釋。 解決方案1的工作方式就像一個魅力......當我試圖將我的腳本添加到列表中時,我將它添加爲第二個,order order = | – danielfranca

+1

作爲評論,在這種情況下,你不需要'web_accessible_resources'。事實上,它可能被認爲是有害的:你將自己暴露給指紋,因爲任何事情都可以嘗試在你的擴展中請求知名資源。 – Xan

相關問題