javascriptgoogle-chrome-extensionopera-extension

How can a Chrome extension check at runtime if it is running on Opera?


Since Opera supports the Chrome extension API, it is almost possible to run a full-featured Chrome extension on this browser. However there are still some missing features in the API.

Is there a simple and efficient way to check if an extension is currently running on Opera or Google Chrome?


The specific use case I'm facing is when invoking chrome.notifications.create: on Google Chrome it is possible to set a buttons attribute to add buttons to it. Opera does not support it and instead of ignoring the attribute, it throws an error:

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

So I need a way to check the browser beforehand instead of handling the error.


Solution

  • You're asking the wrong question in the title. If the notification button works in Chrome but not in Opera, then don't try to detect Opera, but detect that buttons are not working and provide a fallback. For instance:

    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');
        }
    });
    

    If you run into a case where you do want to detect an Opera extension environment and use an Opera-specific extension API, you could use typeof opr == 'object' (which is the namespace for Opera-only extension APIs).

    Otherwise, you could use UA-sniffing to distinguish Opera from Chrome: /OPR/.test(navigator.userAgent).

    If you just want to detect a specific version of Chrome/Opera (e.g. because of a browser bug that cannot be detected in any way), use user agent sniffing (How to find the version of Chrome browser from my extension?).