你在标题中问了错误的问题。如果通知按钮在 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 浏览器的版本?)。