2

这是我第一次尝试构建 chrome 扩展。我举了第一个例子,并根据我的需要对其进行了主题化。

我想构建一个 chrome 扩展程序,可以从弹出菜单中控制不同选项卡上的 youtube 播放器。

首先,我想显示所有打开的 youtube 标签的列表。这工作正常。之后,我想在每个选项卡中插入一个脚本。

那就是问题发生的地方:开发人员控制台给了我以下错误

Error during tabs.executeScript: Unknown error.      sendRequest:22
    chromeHidden.handleResponse                      sendRequest:22
Callback worked 

我的 manifest.json 看起来像这样

{
  "manifest_version": 2,

  "name": "YoutubeMusicControl",
  "description": "First Try",
  "version": "1.0",

  "permissions": [
    "tabs",
    "http://*/",
    "https://*/"
  ],

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}

popup.html 除了运行脚本之外没有什么特别的。

这是有趣的部分

var TabControl = {

    listCurrentTabs : function(){
        var name = "";
        var div;

        chrome.tabs.query({}, function(tabs){

            for(var i = 0; i < tabs.length; i++){

                var found = tabs[i].url.search(/.*youtube.*/);

                if(found != -1){
                    div = document.createElement('div');

                    name = tabs[i].title;
                    div.className = "entry";
                    div.innerHTML = name;
                    document.body.appendChild(div);                  

                    chrome.tabs.executeScript(i,{
                        code:"alert('test');"
                    },function(results){console.log("Callback worked")});
                    }                    
                }
        });
    }
}

document.addEventListener('DOMContentLoaded', function () {
  TabControl.listCurrentTabs();
});

如果我将参数 i 更改为 null(当前选项卡),一切正常。看起来好像我没有权限或参数有问题,但我无法让代码工作。

Can somebody see why the code is not working?

Thanks in advance

4

1 回答 1

4

Your answer lies in the parameters of executeScript. If you do not speciy a tabID, it defaults to your current active tab (this is what happens when you feed it null).

However, when you feed it that optional integer, you need to be aware that this integer is not the index of the tab in the tablist, but its actual ID (can be acquired using tab[i].id in your case).

Using the unique ID of the tab will make your code work. Just change executeScript(i to executeScript(tabs[i].id

于 2013-05-20T12:13:24.313 回答