0

如果他们在 youtube.com 上,我基本上只是想获取当前的标签 URL。我不断从脚本中收到错误消息。

Error:

Uncaught TypeError: Cannot call method 'getSelected' of undefined

显现

{
    "name": "YouTube Fix",
    "version": "0.0.1",
    "manifest_version": 2,
    "description": "Fix some of the annoying little things in YouTube.",
    "icons": {
        "16": "icon.png",
        "48": "icon.png",
        "128": "icon.png"
    },
    "content_scripts": [{
        "matches": ["http://www.youtube.com/*"],
        "js": ["background.js"],
        "run_at": "document_start"
    }],
    "permissions": ["tabs"]
}

背景.js

//this is what is giving me the error:
chrome.tabs.getSelected(null, function (tab) {
    myFunction(tab.url);
});

function myFunction(tablink) {
    if (tablink == "http://www.youtube.com") {
        window.location = "http://www.youtube.com/feed/subscriptions/u";
    }
    document.getElementById("comments-textarea").disabled = false;
}
4

4 回答 4

2

以下分叉很好,不需要chrome.tabs.getSelected(null, function (tab) {}),因为您的页面总是运行"matches": ["http://www.youtube.com/*"],

更多地将此条件添加到您的代码中if(document.getElementById("comments-textarea") != null){

工作背景.js

 if (window.location == "http://www.youtube.com") {
        window.location = "http://www.youtube.com/feed/subscriptions/u";
    }
    if (document.getElementById("comments-textarea") != null) {
        document.getElementById("comments-textarea").disabled = false;
    }

清单.json

{
    "name": "YouTube Fix",
    "version": "0.0.1",
    "manifest_version": 2,
    "description": "Fix some of the annoying little things in YouTube.",

    "content_scripts": [{
        "matches": ["http://www.youtube.com/*"],
        "js": ["background.js"],
        "run_at": "document_start"
    }],
    "permissions": ["tabs"]
}

如果您需要更多信息,请与我们联系。

于 2012-12-09T23:57:40.953 回答
1

您将 background.js 作为内容脚本而不是背景或事件页面运行,并且https://developer.chrome.com/extensions/content_scripts.html说“内容脚本有一些限制。它们不能......使用 chrome。 * API(chrome.extension 的一部分除外)"

相反,你应该把类似的东西

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

进入你的清单。有关更多详细信息,请参阅https://developer.chrome.com/extensions/event_pages.html

于 2012-12-09T23:25:17.220 回答
0

从这里引用: https ://groups.google.com/a/chromium.org/forum/?fromgroups=#!topic/chromium-extensions/A5bMuwCfBkQ

chrome.tabs.getSelected() 已弃用。以下页面说明了如何改用 chrome.tabs.query: http ://code.google.com/chrome/extensions/whats_new.html#16相关的文本位是:“””方法 getAllInWindow() 和 getSelected () 已被弃用。要获取有关指定窗口中所有选项卡的详细信息,请使用带有参数 {'windowId': windowID} 的 chrome.tabs.query()。要获取在指定窗口中选择的选项卡,请使用 chrome .tabs.query() 带有参数 {'active': true}. """

于 2012-12-09T22:51:50.153 回答
0

chrome.tabs.getSelected弃用。改用chrome.tabs.query

chrome.tabs.query({
    "active": true
}, function(tab){
    console.log(tab[0]);  //selected tab
});

此外,内容脚本无法访问 chrome.tabsAPI。做这个:

chrome.extension.getBackgroundPage().chrome.tabs.query(...

(这可能不起作用。未经测试。)

于 2012-12-09T23:24:47.627 回答