由于Opera支持Chrome扩展程序API,因此几乎可以在此浏览器上运行功能齐全的Chrome扩展程序。但是,API中仍然缺少一些功能。
是否有一种简单有效的方法来检查扩展程序当前是否在Opera或Google Chrome上运行?
我遇到的特定用例是在调用时chrome.notifications.create
:在Google Chrome上可以设置buttons
属性以向其添加按钮。Opera不支持它,并且引发忽略错误,而不是忽略该属性:
Unchecked runtime.lastError while running notifications.create: Adding buttons to notifications is not supported.
因此,我需要一种预先检查浏览器而不是处理错误的方法。
您在标题中提出了错误的问题。如果通知按钮在Chrome中可用,但在Opera中不起作用,则不要尝试检测Opera,而要检测到该按钮不起作用并提供备用。例如:
var options = {
type: 'basic',
iconUrl: '/icon.png',
title: 'My notification',
message: 'My message',
buttons: [{
title: 'Button text',
}],
};
chrome.notifications.create(options, function onCreatedCallback() {
var lastError = chrome.runtime.lastError;
if (lastError && lastError.message === 'Adding buttons to notifications is not supported.') {
delete options.buttons;
chrome.notifications.create(options, onCreatedCallback);
} else if (lastError) {
console.warn('Failed to create notification: ' + lastError.message);
} else {
console.log('Created notification');
}
});
如果遇到确实要检测Opera扩展环境并使用Opera特定扩展API的情况,则可以使用typeof opr == 'object'
(这是仅Opera扩展API的名称空间)。
否则,您可以使用UA嗅探来区分Opera和Chrome :/OPR/.test(navigator.userAgent)
。
如果您只想检测特定版本的Chrome / Opera(例如,由于无法以任何方式检测到浏览器错误),请使用用户代理嗅探(如何从我的扩展程序中找到Chrome浏览器的版本?)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句