【问题标题】:Background page not detecting string in URL properly后台页面未正确检测 URL 中的字符串
【发布时间】:2013-03-05 20:48:33
【问题描述】:

我正在尝试在我的后台页面中设置一个侦听器,当标签在其 URL 中使用“nytimes.com”更新时将增加一个计数器(最终我希望它在使用“NYTimes”更新标签时增加.com”在其标题中,但首先要做的事)。我的代码如下:

// storage for counts
if (localStorage.getItem('nyt') == undefined || localStorage.getItem('nyt') == NaN)
{
    localStorage.setItem('nyt', 0);
}

// turn the value from localStorage into an incrementable int
var nytCount = parseInt(localStorage.getItem('nyt'));

// listen for changed tabs and check URL
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    debugger;
    var url = changeInfo.url;
    if (changeInfo.status == 'complete' && url && url.indexOf("nytimes.com") !== -1) {
        localStorage.setItem('nyt', ++nytCount);
    }
});

后台页面在manifest.json中声明如下:

...
"background": {
    "scripts": ["eventPage.js"],
    "persistent": false
},
...

我也尝试过将“持久”声明为真的,但这似乎并没有奏效。感谢您的帮助。

【问题讨论】:

    标签: javascript html google-chrome google-chrome-extension local-storage


    【解决方案1】:

    我最近完成了我的第一个扩展,所以我不知道我是否有最好的方法,但我能够使用chrome.webRequest.onBeforeRequest.addListener() 在标签中检查主机。

    我必须在manifest 文件中将"webRequest" 添加到permissions,当匹配时,它会触发一个回调,然后可以根据需要做出反应。在我的情况下,我重定向了浏览器,但在你的情况下可以增加你的计数器。

    我写了this blogpost about how I created my chrome extension,希望对你有帮助。

    【讨论】:

    • 谢谢,我去看看。在另一篇文章中,有人告诉我最好的方法可能是使用 chrome.tabs,所以希望有人能在这方面给我一些指导。
    • 我实际上似乎已经明白了 - 如果你有兴趣,这就是我使用的: chrome.tabs.onUpdated.addListener(function(url, changeInfo, Tab) { chrome.tabs.getSelected(空,函数(标签){ var title = tab.title; if (title.indexOf("NYTimes.com") != -1 && changeInfo.status == "complete") { localStorage.setItem('nyt', + +nytCount); } }); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多