2016-11-07 59 views
1

在我的一個組件中,當組件加載時,我希望我的擴展將腳本注入到運行擴展的當前選項卡中。該腳本實質上獲取源代碼並將其保存爲字符串。如何在反應中使用tabs.executeScript

所以,在我componentWillMount我試圖注入腳本以下列方式...

componentWillMount() { 

    var result = ''; 
    chrome.tabs.executeScript(null, { 
     file: './js/scripts/getPageSource.js' 
    }, function() { 
     // If you try and inject into an extensions page or the webstore/NTP you'll get an error 
     if (chrome.runtime.lastError) { 
      result = 'There was an error injecting script : \n' + chrome.runtime.lastError.message; 

     } 
    }); 
} 

我的腳本的路徑,./js/scripts/getPageSource.js是相對於我的index.html文件正在使用我的應用程序的反應。

我得到的錯誤文件沒有找到,所以我改變了相對於組件的路徑,但我仍然找不到文件。

我在想也許這不是正確的方式注入一個腳本到反應的開放標籤,有沒有更好的方式做到這一點?

編輯

這是我manifest.json文件...

{ 
    "name": "Get pages source", 
    "version": "1.0", 
    "manifest_version": 2, 
    "description": "Get pages source from a popup", 
    "browser_action": { 
    "default_popup": "src/index.html" 
    }, 
    "permissions": ["tabs", "<all_urls>"] 
} 

我的路徑./js/scripts/getPageSource.js位於我src文件夾內被上述

+0

@Makyen如果你需要我補充清單文件和腳本調用,我可以這樣做。但我的主要問題是我試圖注入一個腳本,並沒有被調用。據我所知,你不需要知道劇本對你的作用是什麼? – Bolboa

+0

@Makyen好吧我添加了它 – Bolboa

回答

3

使用是相對路徑引用您的manfest.json文件。

MDN states:

在Firefox中,相對URL是相對於當前頁面的URL解決。在Chrome中,這些網址是,相對於加載項的基本網址已得到解決。

從你的manifest.json,它看起來像你的file應該是:

file: 'src/js/scripts/getPageSource.js'