How can I add a click for pageAction?

余生长醉 提交于 2020-01-03 13:35:23

问题


First extension—please be kind.

My objective is to offer an option when a user visits pages from a particular domain to offer an option to launch another page which uses part of the visited page's domain name as a variable.

This code below does what I want but it doesn't offer the action as an option—it just executes.

When a page that matches the domain is visited it adds an icon to the address bar. I want the new page called to loaded only when the user clicks on that icon. If that's not possible, please suggest an alternative.

Thanks!

function checkForValidUrl(tabId, changeInfo, tab) {

  if (tab.url.indexOf('.foo.com') > -1) {

    chrome.pageAction.show(tabId);
    var myName = tab.url.split(".")[0].slice(7);

    if (myName != "www"){ //ignore main site

    chrome.tabs.update(tab.id, {url: "http://foo.com/foo.html?t=" + myName});
    }

  }
};

chrome.tabs.onUpdated.addListener(checkForValidUrl);

回答1:


You just need to use chrome.pageAction.onClicked. For example:

function checkForValidUrl(tabId, changeInfo, tab) {
  if (tab.url.indexOf('.foo.com') > -1) 
    chrome.pageAction.show(tabId);
};

chrome.tabs.onUpdated.addListener(checkForValidUrl);

chrome.pageAction.onClicked.addListener(function(tab){
  var myName = tab.url.split(".")[0].slice(7);
  if (myName != "www") //ignore main site
    chrome.tabs.update(tab.id, {url: "http://foo.com/foo.html?t=" + myName});
});



回答2:


Above answer is correct but note that you'll need to have the correct permissions in the manifest for this to work or the tab.url will be undefined.

From the docs The URL the tab is displaying. This property is only present if the extension's manifest includes the "tabs" permission.

Link - https://developer.chrome.com/extensions/tabs#type-Tab



来源:https://stackoverflow.com/questions/15711369/how-can-i-add-a-click-for-pageaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!