gpt4 book ai didi

javascript - 使用函数触发 chrome.browserAction.onClicked

转载 作者:数据小太阳 更新时间:2023-10-29 04:16:20 27 4
gpt4 key购买 nike

我想触发点击,下面的代码正在监听:

chrome.browserAction.onClicked.addListener(function(tab) {});

原因是我有一个工作扩展,它在后台脚本(上面的 addListener)中监听并在点击时执行一些脚本:

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {file: 'abc.js'});
chrome.tabs.executeScript(tab.id, {file: 'xxx.js'});
});

现在我想从上下文菜单中触发这个“onClicked”:

var myContextPage = chrome.contextMenus.create({"title": myTitle, "contexts":["page"],
"onclick": fctContext});

因此,我认为最简单的方法是在 fctContext 中进行“单击”。也许有更好的方法,但我不知道如何解决我的问题。我也尝试运行“executeScript”,但这也不起作用。

提前致谢!

//更新

答案的解决方案:此解决方案有效:

//Shared code. When the argument length is two, it is coming from the context
// menu, while a single argument is coming from the browser action.
function fctContext() {
var tab = arguments.length == 2 ? arguments[1] : arguments[0];
// Do whatever you want with the tab.
}

// Browser Action
chrome.browserAction.onClicked.addListener(fctContext);

// Context Menu
chrome.contextMenus.create({
title: myTitle,
contexts: ['page'],
onclick: fctContext
});

测试一些其他东西后的解决方案:

function fctStart() {
chrome.tabs.getSelected(null, function(tab){
chrome.tabs.executeScript(tab.id, {file: 'abc.js'});
chrome.tabs.executeScript(tab.id, {file: 'xxx.js'});
});
}

在这种情况下,fctStart() 从任意点开始工作,无需通过制表符。

最佳答案

请记住,参数在 JavaScript 中是可选的。每个函数都有一个关联的 arguments 对象。该参数充当数组。在您的情况下,其中一个需要,而另一个则不需要。在一个函数(浏览器操作)中有 N 个参数与在另一个函数(上下文菜单)中有 M 个参数相同,这两个参数之间的唯一区别是 arguments.callee 提供了一种引用方式函数本身的实际代码。如果您想要一些基本的东西,则不必担心。

您的 fctContext 可以是您的 browserAction 点击​​和上下文菜单之间的可共享代码。我在 Reload All Tabs 扩展中做了类似的事情。

https://github.com/mohamedmansour/reload-all-tabs-extension/blob/master/js/reload_controller.js 中搜索 this.reload ,您会注意到 this.reload 被用于上下文菜单和浏览器操作。您只需共享代码。

已更新参数示例:

在您的情况下,您执行完全相同的操作。

// Shared code. When the argument length is two, it is coming from the context
// menu, while a single argument is coming from the browser action.
function fctContext() {
var tab = arguments.length == 2 ? arguments[1] : arguments[0];
// Do whatever you want with the tab.
}

// Browser Action
chrome.browserAction.onClicked.addListener(fctContext);

// Context Menu
chrome.contextMenus.create({
title: myTitle,
contexts: ['page'],
onclick: fctContext
});

上述方法的问题是可维护性,如果 API 更改,它可能会中断。就个人而言,我宁愿明确地命名参数。因此用户不必在参数数组中进行查找。

function fctContext(tab) {
// Do whatever you want with the tab.
}

// Browser Action
chrome.browserAction.onClicked.addListener(fctContext);

// Context Menu
chrome.contextMenus.create({
title: myTitle,
contexts: ['page'],
onclick: function (detail, tab) { fctContext(tab) }
});

希望对您有所帮助!

关于javascript - 使用函数触发 chrome.browserAction.onClicked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6499471/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com