2014-02-20 36 views
1

我試圖讓我的頁面動作圖標顯示在特定的網址上。我試過實現here的例子,但是這些需要trunk/dev版本。顯示頁面特定網址上的動作圖標

我現在的代碼取自a SO answer。但是這似乎不起作用,因爲該選項卡對象從未在我的測試中具有可限制的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

這個工作對我來說:

//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

+0

這裏是什麼的'〜tab.url.indexOf(」的含義。 pl')' –

+0

'〜。「String」.indexOf(「S」)'是判斷字符串是否包含子字符串的智能方法。 '〜'爲'-1'返回0,即indexOf找不到匹配項。請參閱JS文檔中的〜運算符。 –

0

我遲到回答這個問題,但是這可能會幫助其他人有同樣的問題。我只花了大約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]) 
    }) 
}) 
相關問題