0

由于 Opera 支持 Chrome 扩展 API,因此几乎可以在此浏览器上运行功能齐全的 Chrome 扩展。但是,API 中仍然缺少一些功能。

是否有一种简单有效的方法来检查扩展程序当前是否在 Opera 或 Google Chrome 上运行?


我面临的具体用例是调用时chrome.notifications.create:在谷歌浏览器上,可以设置一个buttons属性来添加按钮。Opera 不支持它,而不是忽略该属性,它会抛出一个错误:

Unchecked runtime.lastError while running notifications.create: Adding buttons to notifications is not supported.

所以我需要一种方法来事先检查浏览器而不是处理错误。

4

2 回答 2

3

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

于 2015-09-26T13:05:22.410 回答
0

如何确定您的扩展后台脚本正在哪个浏览器中执行?

var isOpera = (!!window.opr && !!opr.addons) || !!window.opera ||
    navigator.userAgent.indexOf(' OPR/') >= 0;
于 2020-04-17T22:34:35.277 回答