4

我是 chrome 扩展编程的新手,这是/将是我的第一个扩展。

我想要什么:现在我想为页面做一个 pageAction,如果显示了某个 html-tag。要执行 pageAction 似乎我必须知道当前选项卡的 TabID,所以我尝试了这个,它不起作用(参见代码中的注释):

manifest.json(效果很好,只是为了向您展示我的清单的样子)

{
    "manifest_version":2,

    "name":"ExtensionName",
    "description":"Description",
    "version":"1.0",

    "page_action":{
        "default_icon":"icon.png",
    },
    "content_scripts":[
        {
            "matches":[
                "http://www.domain.com/page.aspx"
            ],
            "js":["searchTag.js"],
            "run_at":"document_idle",
            "all_frames":false
        }
    ]
}

searchTag.js(代码或多或少类似于 Arithmomaniac如何从后台页面获取当前 tabId的答案)

if (document.getElementById("idIWant")) {
    var currentTab;
    alert(currentTab);  //this works and gives an alert with "undefined"
    //now the alert in the function callback doesn't work
    chrome.tabs.query(
        {currentWindow: true, active: true},
        function(tabArray) {
            alert(tabArray[0].id);
            currentTab = tabArray[0].id;
        }
    )
}

那么我的代码有什么问题?似乎我没有正确使用 chrome.tabs.query() 但我没有看到它。

4

1 回答 1

7

searchTag.js 是一个内容脚本( https://developer.chrome.com/extensions/content_scripts.html ),它无法访问chrome.tabsAPI。您必须从内容脚本向后台页面 ( https://developer.chrome.com/extensions/messaging.html ) 发送消息,并在后台页面中调用 chrome.tabs.query。例如:

searchTag.js

if (document.getElementById("idIWant")) {
    chrome.runtime.sendMessage('showPageAction');
}

bg.js

var currentTab;

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request == 'showPageAction') {
    chrome.tabs.query(
        {currentWindow: true, active: true},
        function(tabArray) {
            if (tabArray && tabArray[0])
                chrome.pageAction.show(tabArray[0].id);
        }
    );
    // sender will also contain the tab id so you can simply use
    // if (sender)
    //     chrome.pageAction.show(sender.tab.id);
  }
});

并将其添加到 manifest.json

"background": {
  "scripts": ["bg.js"],
  "persistent": true
},
于 2013-08-15T11:39:23.417 回答