首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我如何使浏览器动作按钮看起来和行为像一个按钮

我如何使浏览器动作按钮看起来和行为像一个按钮
EN

Stack Overflow用户
提问于 2016-11-15 06:45:36
回答 1查看 1.8K关注 0票数 5

目标是为火狐获取一个WebExtension,它可以被工具栏中的用户激活/停用,比如开/关开关。

我使用的是background.js和下面的代码:

代码语言:javascript
复制
browser.browserAction.onClicked.addListener(function (tab) {
    switch (button) {
        case 'turn-on':
            enable();
            break;
        case 'turn-off':
            disable();
            break;
    }
});
function enable() {
    browser.browserAction.setIcon({ path: '/ui/is-on.png', });
    browser.browserAction.setPopup({ popup: '/ui/turn-off.js', });
    browser.webNavigation.onCommitted.addListener(onTabLoad); 
} 
function disable() {
    browser.browserAction.setIcon({ path: '/ui/is-off.png', });
    browser.browserAction.setPopup({ popup: '/ui/turn-on.js', });
    browser.webNavigation.onCommitted.removeListener(onTabLoad); 
}
function onTabLoad(details) {
    browser.tabs.executeScript(details.tabId, {
        file: '/gc.js',
        allFrames true,
    }); 
}
enable(); // enable or disable by default

很明显我做错了什么。我是个编码新手。这是我想要完成的个人项目。

EN

回答 1

Stack Overflow用户

发布于 2016-11-15 07:35:28

你的代码

在添加switch语句以打开button时,您从未定义过button,也没有更改过它的状态。您也没有默认情况,以防button变量不是您在case语句中测试的值之一。

您不应该使用browserAction.setPopup()设置弹出窗口。设置弹出窗口将导致弹出窗口被打开,而不是您的后台页面接收click事件。此外,弹出窗口需要是一个HTML页面,而不是JavaScript。

请参阅下面一节中需要在onTabLoad()中处理的Firefox。

webNavigation.onCommitted并不足以涵盖脚本何时需要注入的所有情况。换句话说,webNavigation.onCommitted并不是每次加载页面时都会触发。为了充分解决脚本需要注入的每一种情况,您需要在另一个问题中提出。

代码语言:javascript
复制
var nextButtonState;
browser.browserAction.onClicked.addListener(function (tab) {
    switch (nextButtonState) {
        case 'turn-on':
            enable();
            break;
        case 'turn-off':
        default:
            disable();
            break;
    }
});
function enable() {
    browser.browserAction.setIcon({ path: '/ui/is-on.png', });
    //browser.browserAction.setPopup({ popup: '/ui/turn-off.js', });
    browser.webNavigation.onCommitted.addListener(onTabLoad); 
    nextButtonState = 'turn-off';
} 
function disable() {
    browser.browserAction.setIcon({ path: '/ui/is-off.png', });
    //browser.browserAction.setPopup({ popup: '/ui/turn-on.js', });
    browser.webNavigation.onCommitted.removeListener(onTabLoad); 
    nextButtonState = 'turn-on';
}
function onTabLoad(details) {
    //Add a setTimout to avoid a Firefox bug that Firefox is not quite ready to 
    //  have tabs.executeScript() inject a script when the onCommitted event fires.
    setTimeout(function(){
        chrome.tabs.executeScript(details.tabId, {
            file: '/gc.js',
            allFrames true,
        }); 
    },0);
}
enable(); // enable or disable by default

解决火狐webNavigation.onCommitted错误的方法

需要对onTabLoad()代码进行更改,以便使用webNavigation.onCommitted侦听器在火狐中使用tabs.executeScript()注入脚本(Chrome中不需要这样做)。这是因为火狐中有一个错误,如果从tabs.executeScript()侦听器立即执行,会导致webNavigation.onCommitted失败。我使用的解决方法是在setTimeout(function,0)延迟之后注入脚本。这使火狐能够执行设置executeScript()所需的环境所需的代码。

代码语言:javascript
复制
function onTabLoad(details) {
    //Add a setTimout to avoid a Firefox bug that Firefox is not quite ready to 
    //  have tabs.executeScript() inject a script when the onCommitted event fires.
    setTimeout(function(){
        chrome.tabs.executeScript(details.tabId, {
            file: '/gc.js',
            allFrames true,
        }); 
    },0);
}

多状态按钮(例如切换按钮)的广义解

下面是我用来使Browser Action按钮像按钮一样运行的代码。我修改了browserButtonStates对象,它既描述了按钮的功能,也描述了它们的外观,以添加和删除webNavigation.onCommitted侦听器onTabLoad()。有关onTabLoad()的问题,请参阅上面的内容。

下面的代码比您需要的要复杂得多。我编写它的目的是只需要更改browserButtonStates对象的内容,就可以将它从一个项目转移到另一个项目。然后,仅通过更改该对象,就可以更改在每种状态(例如,on/off)中执行的图标、文本、徽章文本、徽章颜色和操作。

background.js

代码语言:javascript
复制
//The browserButtonStates Object describes the states the button can be in and the
//  'action' function to be called when the button is clicked when in that state.
//  In this case, we have two states 'on' and 'off'.
//  You could expand this to as many states as you desire.
//icon is a string, or details Object for browserAction.setIcon()
//title must be unique for each state. It is used to track the state.
//  It indicates to the user what will happen when the button is clicked.
//  In other words, it reflects what the _next_ state is, from the user's
//  perspective.
//action is the function to call when the button is clicked in this state.
var browserButtonStates = {
    defaultState: 'off',
    on: {
        icon         : '/ui/is-on.png'
        //badgeText  : 'On',
        //badgeColor : 'green',
        title        : 'Turn Off',
        action       : function(tab) {
                           chrome.webNavigation.onCommitted.removeListener(onTabLoad);
                       },
        nextState    : 'off'
    },
    off: {
        icon         : '/ui/is-off.png'
        //badgeText  : 'Off',
        //badgeColor : 'red',
        title        : 'Turn On',
        action       : function(tab) {
                           chrome.webNavigation.onCommitted.addListener(onTabLoad);
                       },
        nextState    : 'on'
    }
}

//This moves the Browser Action button between states and executes the action
//  when the button is clicked. With two states, this toggles between them.
chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.browserAction.getTitle({tabId:tab.id},function(title){
        //After checking for errors, the title is used to determine
        //  if this is going to turn On, or Off.
        if(chrome.runtime.lastError){
            console.log('browserAction:getTitle: Encountered an error: ' 
                + chrome.runtime.lastError);
            return;
        }
        //Check to see if the current button title matches a button state
        let newState = browserButtonStates.defaultState;
        Object.keys(browserButtonStates).some(key=> {
            if(key === 'defaultState') {
                return false;
            }
            let state = browserButtonStates[key];
            if(title === state.title) {
                newState = state.nextState;
                setBrowserActionButton(browserButtonStates[newState]);
                if(typeof state.action === 'function') {
                    //Do the action of the matching state
                    state.action(tab);
                }
                //Stop looking
                return true;
            }
        });
        setBrowserActionButton(browserButtonStates[newState]);
    });
});

function setBrowserActionButton(tabId,details){
    if(typeof tabId === 'object' && tabId !== null){
        //If the tabId parameter is an object, then no tabId was passed.
        details = tabId;
        tabId       = null;
    }
    let icon   = details.icon;
    let title  = details.title;
    let text   = details.badgeText;
    let color  = details.badgeColor;

    //Supplying a tabId is optional. If not provided, changes are to all tabs.
    let tabIdObject = {};
    if(tabId !== null && typeof tabId !== 'undefined'){
        tabIdObject.tabId = tabId;
    }
    if(typeof icon === 'string'){
        //Assume a string is the path to a file
        //  If not a string, then it needs to be a full Object as is to be passed to
        //  setIcon().
        icon = {path:icon};
    }
    if(icon) {
        Object.assign(icon,tabIdObject);
        chrome.browserAction.setIcon(icon);
    }
    if(title) {
        let detailsObject = {title};
        Object.assign(detailsObject,tabIdObject);
        chrome.browserAction.setTitle(detailsObject);
    }
    if(text) {
        let detailsObject = {text};
        Object.assign(detailsObject,tabIdObject);
        chrome.browserAction.setBadgeText(detailsObject);
    }
    if(color) {
        let detailsObject = {color};
        Object.assign(detailsObject,tabIdObject);
        chrome.browserAction.setBadgeBackgroundColor(detailsObject);
    }
}

//Set the starting button state to the default state
setBrowserActionButton(browserButtonStates[browserButtonStates.defaultState]);

manifest.json

代码语言:javascript
复制
{
    "description": "Demo Button toggle",
    "manifest_version": 2,
    "name": "Demo Button toggle",
    "version": "0.1",

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

    "browser_action": {
        "default_icon": {
            "32": "myIcon.png"
        },
        "default_title": "Turn On",
        "browser_style": true
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40603655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档