后台页面可以使用window.location
Can background page use window.location
我正在尝试创建 chrome 扩展程序,它将从我的网页中删除数据,然后将其显示在浏览器操作中 window。我想为此使用背景页面,因为如果我正确理解扩展,它是唯一能够不间断工作的元素,不需要可见的选项卡。
问题是,当我使用 background.js:
时,我为 background.js 编写的脚本不能正常工作
var location = window.location.href = 'http://localhost/index.php';
console.log(location);
manifest.json:
"background": {
"scripts": ["src/background/background.js"]
},
我得到的答案是 chrome-extension://some_random_text/_generated_background_page.html.
是否可以使用后台页面导航到我的网页,然后填写一些表格和剪贴数据以备后用?
一个chrome扩展有两个主要部分,扩展进程和浏览器本身。后台页面在扩展过程中工作。它没有关于您的网页的直接访问和信息。
要让脚本在您的网页上不间断运行,您需要使用 Content Scripts。
然后您可以使用 messages
在您的内容脚本和后台页面之间进行通信
contentScript.js
var location = window.location.href = 'http://localhost/index.php';
chrome.runtime.sendMessage({location: location}, function(response) {});
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(request.location);
});
这是一个老问题,但我最近想做同样的事情。
所以我会为其他有兴趣的人提供答案。
设置 window.location 在 Chrome52 中仍然不起作用。
不过有一个解决方法。可以先用fetch()获取网页,然后用document.write设置内容
这很好用,然后您可以查询文档并用它做任何您想做的事情。
这是一个例子。 (请注意,我正在使用提取 API、箭头函数和 LET,它们现在在 Chrome52 中都可以正常工作)。
fetch("http://cnn.com").then((resp) => {
return resp.text();
}).then((html) => {
document.open("text/html");
document.write(html);
document.close();
// IMPORTANT: need to use setTimeout because chrome takes a little
// while to update the document.
setTimeout(function() {
let allLinks = document.querySelectorAll('a');
// Do something with the links.
}, 250);
});
我正在尝试创建 chrome 扩展程序,它将从我的网页中删除数据,然后将其显示在浏览器操作中 window。我想为此使用背景页面,因为如果我正确理解扩展,它是唯一能够不间断工作的元素,不需要可见的选项卡。
问题是,当我使用 background.js:
时,我为 background.js 编写的脚本不能正常工作var location = window.location.href = 'http://localhost/index.php';
console.log(location);
manifest.json:
"background": {
"scripts": ["src/background/background.js"]
},
我得到的答案是 chrome-extension://some_random_text/_generated_background_page.html.
是否可以使用后台页面导航到我的网页,然后填写一些表格和剪贴数据以备后用?
一个chrome扩展有两个主要部分,扩展进程和浏览器本身。后台页面在扩展过程中工作。它没有关于您的网页的直接访问和信息。
要让脚本在您的网页上不间断运行,您需要使用 Content Scripts。
然后您可以使用 messages
在您的内容脚本和后台页面之间进行通信contentScript.js
var location = window.location.href = 'http://localhost/index.php';
chrome.runtime.sendMessage({location: location}, function(response) {});
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(request.location);
});
这是一个老问题,但我最近想做同样的事情。 所以我会为其他有兴趣的人提供答案。
设置 window.location 在 Chrome52 中仍然不起作用。 不过有一个解决方法。可以先用fetch()获取网页,然后用document.write设置内容
这很好用,然后您可以查询文档并用它做任何您想做的事情。
这是一个例子。 (请注意,我正在使用提取 API、箭头函数和 LET,它们现在在 Chrome52 中都可以正常工作)。
fetch("http://cnn.com").then((resp) => {
return resp.text();
}).then((html) => {
document.open("text/html");
document.write(html);
document.close();
// IMPORTANT: need to use setTimeout because chrome takes a little
// while to update the document.
setTimeout(function() {
let allLinks = document.querySelectorAll('a');
// Do something with the links.
}, 250);
});