在特定网址上显示网页操作图标

时间:2014-02-20 08:34:29

标签: google-chrome-extension

我正在尝试将我的页面操作图标显示在特定网址上。我已尝试实现示例here但这些需要trunk / dev release。

我当前的代码取自a SO answer。但这似乎不起作用,因为tab对象在我的测试中从来没有一个url属性可以限制。

// background.js

function checkURL(tabId, info, tab) {
    if (info.status === "complete") {
        if (tab.url) {
            // restrict here
            chrome.pageAction.show(tabId);
        }
    }
}
chrome.tabs.onUpdated.addListener(checkURL);

//清单

{
    "manifest_version": 2,

    "name": "My first extension",
    "version": "1.0",

    "content_scripts": [
        {
            "matches": ["http://www.google.com/*"],
            "js": [
                "script.js"
            ],
            "run_at": "document_idle"
        }
    ],

    "background": {
       "page": "background.html",
       "persistent": false
    },

    "page_action": {
        "default_icon": "icon.png"
    }
}

我做错了什么?

2 个答案:

答案 0 :(得分:2)

这对我有用:

//background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if (~tab.url.indexOf('.pl')) {
    chrome.pageAction.show(tabId);
  }
});

//manifest.json
"permissions": [
"tabs"
]

我没有使用persistent:false

答案 1 :(得分:1)

我很晚才回答这个问题,但这可能有助于其他人遇到同样的问题。我花了大约20分钟为自己的扩展寻找它。

看这里https://developer.chrome.com/extensions/declarativeContent

将此添加到您的清单

"background" : {
    "scripts": ["background.js"]
}
"permissions" : {
    "declarativeContent"
}

然后在background.js

var rule1 = {
    conditions: [
      new chrome.declarativeContent.PageStateMatcher({
        // If I wanted my extension to work only on SO I would put
        // hostContains: 'stackoverflow.com'
        // You can check out the link above for more options for the rules
        pageUrl: { hostContains: 'some string' } 
      })
    ],
    actions: [ new chrome.declarativeContent.ShowPageAction() ]
};
chrome.runtime.onInstalled.addListener(function (details) {
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
        chrome.declarativeContent.onPageChanged.addRules([rule1])
    })
})
相关问题