如何为特定页面显示page_action?

时间:2012-02-11 22:50:38

标签: javascript google-chrome-extension

我正在玩一些Chrome扩展程序,我找到了这个例子:http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/pageAction/pageaction_by_url/

一切正常,但我想创建自己的扩展,我想在特定网站上看到page_action图标,而不是在网址中看到'g'的图标。 所以我试着简单地改变脚本:

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Called when the url of a tab changes.
function checkForValidUrl(tabId, changeInfo, tab) {
// If the letter 'g' is found in the tab's URL...
if (tab.url.indexOf('g') > -1) {
// ... show the page action.
chrome.pageAction.show(tabId);
}
};

// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);

进入这个:

chrome.pageAction.show(tabId);

但现在它不起作用...... 我不明白。显然我可以使用一种解决方法,但这不是重点......首先,我必须创建一个后台页面来执行此操作吗?我想是的,但我不明白为什么,为什么.show方法不能单独工作? 我试着搜索谷歌文档和东西,但我找不到任何有用的东西,我不是专家,这是我第一个下午花在谷歌扩展,但我怎么知道“chrome.page.show( tabId)“如果没有写在任何地方,必须进入后台页面?没有意图批评,但你们怎么会发现?所有chrome方法都必须放在后台页面中? 那么,肯定有更多的问题,那么它的合法性。希望你能给我至少一个答案!

2 个答案:

答案 0 :(得分:29)

http://code.google.com/chrome/extensions/pageAction.html
... ...说

  

默认情况下,隐藏页面操作。当您显示它时,您指定   应显示图标的选项卡。图标保持可见,直到   选项卡已关闭或开始显示不同的URL(因为   用户单击链接,例如)。

因此,即使您的tabid有效,当您首次运行后台页面时,它也会非常快速地消失,因为您只能运行chrome.pageAction.show(tabId);。 您需要不断检查后台标签的更改,因为pageactions在清单中没有匹配/ exclude_matches设置,就像内容脚本一样(遗憾)。所以你必须检查自己并回应变化 如果您希望它适用于特定网站,只需将其更改为...

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Called when the url of a tab changes.
function checkForValidUrl(tabId, changeInfo, tab) {
    // If the tabs url starts with "http://specificsite.com"...
    if (tab.url.indexOf('http://specificsite.com') == 0) {
        // ... show the page action.
        chrome.pageAction.show(tabId);
    }
};

// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);

答案 1 :(得分:2)

对于那些寻找处理子域名的方法,如果您的网站包含 blog.specificsite.com 等子域名,或者需要使用通配符,您也可以使用此格式的正则表达式

local postgres postgres trust
local mydb mydb md5
local mydb mydb password
host mydb mydb 0.0.0.0/0 password
host mydb mydb 0.0.0.0/0 md5

匹配URL中的子字符串。它还有助于计算进行空/未定义检查以避免其他异常处理。