如果某个功能(例如MediaSource)可用,我该如何使用Google Dart查看。
new MediaSource()会抛出错误。如何以编程方式检查此类或功能是否存在?有任何想法吗?是否有内置功能?
我尝试过try / catch,但看起来我使用的浏览器上的异常类型不同。
编辑#2
youtube.com/html5是这样的:
var mse = window['MediaSource'] || window['WebKitMediaSource'];
setCompatibility('c-mse', !!mse);
我应该只使用jsobject(dart:js包)吗?
问候并感谢, 罗伯特
答案 0 :(得分:3)
我发现了这个:
import 'dart:js';
bool available = context.hasProperty('MediaSource');
有没有人有更好的解决方案?对我来说,这看起来是最干净的解决方案。
问候,罗伯特
答案 1 :(得分:2)
我认为会抛出TypeError,那么如果MediaSource不存在则捕获异常呢?
try {
new MediaSource();
// do something if MediaSource is available
} on TypeError catch(e) {
// do something else if MediaSource is not available
}
答案 2 :(得分:2)
Dart提供特殊注释:
/**
* 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 {
...
您可以检测浏览器版本并获取(使用镜像)表示某个Web功能的类的注释。如果它有@Experimental
,可能@Unstable
,那么即使使用支持的浏览器也无法依赖它。如果它有@SupportedBrowser
注释,并且用户浏览器在列表中或根本没有@SupportedBrowser
,那么你应该没问题。