【问题标题】:Current TabID for pageActionpageAction 的当前 TabID
【发布时间】:2013-08-17 11:20:49
【问题描述】:

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

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

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(代码或多或少类似于 how to get current tabId from background page 中 Arithmomaniac 的回答)

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() 但我没有看到它。

【问题讨论】:

    标签: google-chrome google-chrome-extension tabs


    【解决方案1】:

    searchTag.js 是一个内容脚本 (https://developer.chrome.com/extensions/content_scripts.html),它无法访问chrome.tabs API。您必须从内容脚本向后台页面 (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
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      相关资源
      最近更新 更多