【发布时间】:2015-07-31 14:24:30
【问题描述】:
我正在尝试创建一个简单的 chrome 扩展程序,以在每次访问时从我的历史记录中删除一个 reddit url,然后将其替换为随机的维基百科文章。为此,我有一个内容脚本,它将消息传递给后台脚本以从历史记录中删除其 url:
content_script.js:
window.onload = chrome.runtime.sendMessage({greeting: "do the thing"});
background.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("deleting url " + sender.tab.url);
//chrome.browsingData.removeCache({});
chrome.history.deleteUrl( {url: sender.tab.url},
function () {
console.log("replacing url");
chrome.history.addUrl({url: "https://en.wikipedia.org/wiki/Special:Random"});
}
);
});
我所有的 console.log 打印都确认我的脚本正在正确执行,没有抛出错误(即使在生成的背景页面上)但是当我从 chrome://history 查看我的历史记录时,我访问的所有 reddit url 仍然存在,顶部只有一个维基百科访问。 (image)
这个错误很有趣,因为当我使用 chrome 历史 API 检查历史时,reddit 链接不存在!打印出来的只是一个维基百科链接和我的非 reddit 历史。
function printHistory(){
chrome.history.search({text: '', maxResults: 10},
function(data) {
data.forEach(function(page) {
console.log(page.url);
});
});
}
所以有三个问题
- 不会在 chrome://history 中删除 reddit 网址
- wikipedia url 只添加一次,最后添加一次(或者每次都以某种方式删除并重新添加)。
- https://en.wikipedia.org/wiki/Special:Random 未解析为真实链接
这是一个 git repo,您可以克隆以重现该错误。 https://github.com/rohanp/test
我有 Chrome 版本 44.0.2403.125(64 位)
【问题讨论】:
-
@RobW 关闭历史同步解决了问题 1!谢谢!
-
顺便说一句:你不应该在你的内容脚本中分配给
window.onload。内容脚本可以在 onload 事件之后运行,在这种情况下什么都不会发生。在您的情况下,无论如何您都在执行命令sendMessage并将结果(null?)分配给window.onload。如果您想为window.onload分配一些东西,您应该分配一个函数(但不要使用内容脚本,因为默认情况下内容脚本可能不会接收事件)。
标签: javascript google-chrome google-chrome-extension