当页面动作弹出时,如何判断何时单击页面动作 [英] How to tell when a page action is clicked when the page action has a popup

查看:57
本文介绍了当页面动作弹出时,如何判断何时单击页面动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 https://developer.chrome.com/extensions/pageAction. html#event-onClicked :

chrome.pageAction.onClicked.addListener(function(tabs.Tab tab) {...});

点击页面操作图标时触发.如果页面操作弹出,则不会触发此事件.

Fired when a page action icon is clicked. This event will not fire if the page action has a popup.

那么,如何确定单击页面操作是否使用弹出窗口?

So how do I tell when the page action is clicked if it DOES use a popup?

推荐答案

设置弹出窗口后,单击按钮将导致弹出页面被加载并显示.同时,不会触发onClicked事件.因此,如果要在设置弹出窗口时检测到点击,请在popup.js中添加一些代码.

When a popup is set, clicking on the button causes the popup page to be loaded and displayed. At the same time, the onClicked event will not be triggered. So, if you want to detect a click when a popup is set, put some code in popup.js.

例如:如果您没有弹出窗口的代码如下:

For instance: if your code without popup looks like:

// background/event page
chrome.pageAction.onClicked.addListener(function(tab) {
    // Do something
});

然后从背景/

Then remove that piece of code from the background / event page, and put the code in popup.js:

document.addEventListener('DOMContentLoaded', function() {
    // Do something, e.g. send a message to content or background script
});

如果重要的是将逻辑保留在后台页面中,例如如果您正在发起http请求,数据库访问等,请使用消息传递通知背景页面该按钮已被单击:

If it's important to keep the logic in the background page, e.g. if you're initiating a http request, database access, etc., then use message passing to notify the background page that the button is being clicked:

// popup.js
chrome.runtime.sendMessage('pageActionClicked');

// background.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message === 'pageActionClicked') {
        // Do something
    }
});

如果您必须了解当前选项卡(如pageAction.onClicked事件中的tab参数),请使用 chrome.tabs.query :

If you have to know the current tab (like the tab argument in the pageAction.onClicked event), use chrome.tabs.query:

// Inside the DOMContentLoaded or onMessage event listener:
chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
}, function(tabs) {
    var tab = tabs[0];
    // Do something with tab
});

这篇关于当页面动作弹出时,如何判断何时单击页面动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆