且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在新选项卡中执行内容脚本 - 铬扩展

更新时间:2023-12-05 19:43:40

原因:内容脚本不能用 chrome-extension:// 方案注入到扩展页面。



解决方案:因为您可以控制该html页面,所以请明确引用内容脚本文件。

newpage.html:

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

不要使用 executeScript


I'm trying to create a chrome extension that scrapes some content from a particular website and then opens a new tab and does stuff with the scraped data.

Below is a test I made to see how I might do this. Unfortunately I can't seem to execute the newtab-script.js file as I get this error:

Unchecked runtime.lastError while running tabs.executeScript: Cannot access contents of url "chrome-extension://FAKEIDgfdsgfdsgfdsgdsgfdsgFAKEID/newpage.html". Extension manifest must request permission to access this host. at 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!

Cause: content scripts can't be injected into extension pages with chrome-extension:// scheme.

Solution: since you have control over that html page just reference the content script file explicitly.

newpage.html:

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

And don't use executeScript.