2015-09-26 68 views
0

由於Opera支持Chrome擴展API,因此幾乎可以在此瀏覽器上運行全功能的Chrome擴展。但是API中仍然存在一些缺失的功能。如果Chrome擴展在Opera上運行,它如何在運行時檢查?

是否有一種簡單而有效的方式來檢查擴展程序當前是否在Opera或Google Chrome上運行?


我面臨的具體使用情況是調用chrome.notifications.create時:在谷歌Chrome瀏覽器,可以設置一個buttons屬性按鈕添加到它。 Opera不支持它,而不是忽略的屬性,它拋出一個錯誤:

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

所以我需要一種方法來檢查瀏覽器,而不是事前的處理錯誤。

+0

答案的道理是,如果您想弄清楚某個功能是否可用,那麼您應該使用功能檢測,而不是確定瀏覽器和版本。否則,Opera將執行該功能,但您的擴展程序不起作用。 – Teepeemm

回答

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擴展環境使用歌劇院專用的擴展API,你可以使用typeof opr == 'object'(這是命名空間Opera-only extension APIs)的情況下。

否則,您可以使用UA嗅探區分Opera與Chrome:/OPR/.test(navigator.userAgent)

如果您只想檢測特定版本的Chrome/Opera(例如,由於無法以任何方式檢測到的瀏覽器錯誤),請使用用戶代理嗅探(How to find the version of Chrome browser from my extension?)。

+0

感謝您的答案,但我不想僅僅使用故障回退是因爲我建議我的用戶啓用/禁用此特定按鈕的選項。在Opera上,我想隱藏這個選項,因爲我知道按鈕不受支持。另外,在Opera 32.0中'typeof opr =='object''返回'false'。 – guillaumekln

+0

@guillaumekln只有在清單文件中啓用特定於Opera的API時,'opr'纔可用。總是有效的(沒有擴展名)的另一個選項是檢查UA字符串是否包含「OPR」(請參閱​​更新後的答案)。但即使對於您的特定用例,您也可以使用'chrome.notifications.create',然後使用'chrome.notifications.clear'來查看該功能是否受支持。 –

相關問題