Chrome扩展程序在启用时执行,而不是在单击时执行

时间:2014-02-23 06:42:51

标签: javascript google-chrome google-chrome-extension

这是我的manifest.json

{
    "manifest_version": 2,   

    "name": "PageEscape",
    "version": "1.0",
    "description": "",

    "background": {
        "scripts": ["background.js"]
    },

    "browser_action": {
        "default_icon": "escape_icon.png"
    }
}

这是我的background.js

  chrome.browserAction.onClicked.addListener(window.open("url", "_blank"))

我的目标是让用户在他想要快速切换到另一个页面的时候点击Chrome扩展程序(我现在的选择),但问题是,只要我启用扩展程序,它就会转到网页我选择并单击栏上的扩展名不做任何事情。我可以在这里做些什么才能使这项工作

2 个答案:

答案 0 :(得分:1)

chrome.browserAction.onClicked.addListener( function() {
    window.open("url", "_blank");
});

答案 1 :(得分:0)

试试这样:

var url = 'http://www.example.com/'
chrome.browserAction.onClicked.addListener(function(tab) {
  openPage(url);
});

/**
 * Open the url specified page, there are three cases:
 * 1. If the page has opened, select it;
 * 2. Else if here is a new tab, open the page in the new tab;
 * 3. Else open a new tab in the current window.
 *
 * @param url
 */
function openPage(url) {
  chrome.tabs.query(function (tabs) {
    var newTab = null;

    // search all tabs
    for (var i = 0; i < tabs.length; i++) {
      var tab = tabs[i];

      if (tab.url === url) {
        chrome.tabs.update(tab.id, {url: url, selected: true});
        return;
      } else if (tab.url === 'chrome://newtab/') {
        newTab = tab;
      }
    }

    if (newTab) {
      chrome.tabs.update(newTab.id, {url: url, selected: true});
    } else {
      chrome.windows.getCurrent(function (win) {
        var winId = win.id;
        chrome.tabs.create({windowId: winId, url: url});
      });
    }
  });
}