2014-06-25 58 views
2

如果某個功能(例如MediaSource)可用,如何使用Google Dart進行檢查。檢查(本地)功能/類/功能(例如MediaSource)是否可用/支持

新的MediaSource()引發錯誤。如何以編程方式檢查此類或功能是否存在?有任何想法嗎?有沒有這個內置功能?

我試過try/catch,但它看起來像我使用的瀏覽器中的異常類型不同。

編輯#2

youtube.com/html5確實是這樣的:

var mse = window['MediaSource'] || window['WebKitMediaSource']; 
setCompatibility('c-mse', !!mse); 

所以我應該只使用jsobject(鏢:JS包)?

的問候和感謝, 羅伯特

回答

2

我覺得類型錯誤被拋出,所以關於捕捉異常,如果MediaSource的不存在呢?

try { 
    new MediaSource(); 
    // do something if MediaSource is available 
} on TypeError catch(e) { 
    // do something else if MediaSource is not available 
} 
+0

我已經試過了。有更好的解決方案嗎? – Robert

+0

在Safari中我得到一個'UnknownJavaScriptObject'。 – Robert

+0

我認爲try-catch是最乾淨的解決方案,假設context.hasProperty()在飛鏢<-> js交換中有更多的開銷。 – marfis

3

我發現這一點:

import 'dart:js'; 
bool available = context.hasProperty('MediaSource'); 

有沒有人有一個更好的解決方案?對我來說,這看起來像最乾淨的解決方案。

的問候,羅伯特

2

飛鏢提供特別註明:

/** 
* An annotation used to mark a feature as only being supported by a subset 
* of the browsers that Dart supports by default. 
* 
* If an API is not annotated with [SupportedBrowser] then it is assumed to 
* work on all browsers Dart supports. 
*/ 
class SupportedBrowser { 
    static const String CHROME = "Chrome"; 
    static const String FIREFOX = "Firefox"; 
    static const String IE = "Internet Explorer"; 
    static const String OPERA = "Opera"; 
    static const String SAFARI = "Safari"; 

    /// The name of the browser. 
    final String browserName; 
    /// The minimum version of the browser that supports the feature, or null 
    /// if supported on all versions. 
    final String minimumVersion; 

    const SupportedBrowser(this.browserName, [this.minimumVersion]); 
} 

例如:

@DomName('ApplicationCache') 
@SupportedBrowser(SupportedBrowser.CHROME) 
@SupportedBrowser(SupportedBrowser.FIREFOX) 
@SupportedBrowser(SupportedBrowser.IE, '10') 
@SupportedBrowser(SupportedBrowser.OPERA) 
@SupportedBrowser(SupportedBrowser.SAFARI) 
@Unstable() 
class ApplicationCache extends EventTarget { 
... 

您可以檢測瀏覽器版本,並得到(帶鏡子)一類的註釋代表一些網絡功能。如果它有@Experimental,並且可能是@Unstable,那麼即使支持的瀏覽器也不能依賴它。如果它有@SupportedBrowser註釋和用戶瀏覽器在列表中或根本沒有@SupportedBrowser那麼你應該沒問題。

+1

仍然有點麻煩,但我喜歡這種方法!我希望他們添加允許更輕鬆地檢查支持的功能的屬性。 –

+0

@GünterZöchbauer我認爲你可以製作腳本來導入'dart:html',並將它的註釋(使用鏡像系統)加入到JSON之類的內容中,以避免運行時開銷。例如,該腳本可以作爲變壓器的構建鏈的一部分。 – JAre

+0

對於MediaSource,這不起作用。在Windows7和Windows8.1上使用相同和相同版本的IE11時,會產生不同的結果。由於Win7上的IE11在Windows8.1上不支持MediaSource。因此我更喜歡運行時檢查。 – Robert

相關問題