在新的tab-chrome扩展中执行内容脚本

Execute content script within new tab - chrome extentions

本文关键字:执行 脚本 扩展 tab-chrome      更新时间:2023-09-26

我正在尝试创建一个chrome扩展,它可以从特定网站中抓取一些内容,然后打开一个新的选项卡,并对抓取的数据进行处理。

下面是我做的一个测试,看看如何做到这一点。不幸的是,我似乎无法执行newtab-script.js文件,因为我收到了以下错误:

未选中runtime.last运行tabs.executeScript时出错:无法访问url的内容"铬-extension://FAKEIDgfdsgfdsgfdsgdsgfdsgFAKEID/newpage.html"。扩展清单必须请求访问此主机的权限。在Object.callback(chrome-extension://FAKEIDgfdsgfdsgfdsgdsgfdsgFAKEID/background.js:43:25)

websitescrape.js

var button = document.createElement("button");
button.classList.add("web-scrape");
button.innerHTML = "scrape web";
document.querySelector('.placeIWantToPutButton').appendChild(button);
button.addEventListener('click', scrapeData);
function scrapeData(){
    //do website scraping stuff here...
    var fakedata = [{test:"data1"},{test:"data2"}];
    //send scraped data to background.js
    chrome.runtime.sendMessage({setdata: fakedata}, function(tab){
        //callback
    });
}

background.js

var dataTempStorage = [];
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.setdata) {
        dataTempStorage = request.setdata;
        chrome.tabs.create({
            'url': chrome.extension.getURL('newpage.html')
        }, function(tab) {
            chrome.tabs.executeScript(tab.id, {
                file:chrome.extension.getURL("newtab-script.js")});
        });        
    }
    if (request == "getdata") {
        sendResponse({data: dataTempStorage});
    }    
});

newtab-script.js

chrome.runtime.sendMessage("getdata", function (response) {
    doStuff(response.data);
});
function doStuff(){
    //Do staff on newpage.html with data scraped from original page
}

newpage.html

// page ready to be filled with awesome content!

原因:使用chrome-extension://方案无法将内容脚本注入到扩展页中。

解决方案:因为您可以控制html页面,所以只需显式引用内容脚本文件。

newpage.html:

        <script src="newtab-script.js"></script>
    </body>
</html>

并且不要使用executeScript