Google chrome extension 背景页可以使用window.location吗

Google chrome extension 背景页可以使用window.location吗,google-chrome-extension,Google Chrome Extension,我正在尝试创建chrome扩展,它将从我的网页中删除数据,然后将其显示在浏览器操作窗口中。我想使用背景页来实现这一点,因为如果我正确理解扩展,它是唯一能够不间断工作的元素,而不需要可见的选项卡 问题是,当我使用background.js时,我为background.js编写的脚本无法正常工作: var location = window.location.href = 'http://localhost/index.php'; console.log(location); manifest.j

我正在尝试创建chrome扩展,它将从我的网页中删除数据,然后将其显示在浏览器操作窗口中。我想使用背景页来实现这一点,因为如果我正确理解扩展,它是唯一能够不间断工作的元素,而不需要可见的选项卡

问题是,当我使用background.js时,我为background.js编写的脚本无法正常工作:

var location = window.location.href = 'http://localhost/index.php';
console.log(location);
manifest.json:

"background": {
 "scripts": ["src/background/background.js"]
},
我得到的答案是铬-extension://some_random_text/_generated_background_page.html.


可以使用背景页面导航到我的网页,然后填写一些表格并删除数据以备将来使用?

chrome扩展有两个主要部分,扩展过程和浏览器本身。背景页面用于扩展过程。它无法直接访问您的网页以及您的网页信息

要使脚本在网页上不间断地工作,您需要使用

然后,您可以使用在内容脚本和背景页面之间进行通信

contentScript.js

var location = window.location.href = 'http://localhost/index.php';
chrome.runtime.sendMessage({location: location}, function(response) {});
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(request.location);
    });
background.js

var location = window.location.href = 'http://localhost/index.php';
chrome.runtime.sendMessage({location: location}, function(response) {});
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(request.location);
    });

这是一个老生常谈的问题,但我最近也想做同样的事情。 因此,我将为其他感兴趣的人提供答案

设置window.location在Chrome52中仍然不起作用。 不过,还有一个变通办法。您可以先使用fetch()获取网页,然后使用document.write设置内容

这很好,然后您就可以查询文档并使用它执行任何操作

这里有一个例子。(请注意,我使用的是fetchAPI、arrow函数和LET,它们现在在Chrome52中都可以正常工作)


我在我的博客上对此进行了更详细的介绍: