I'd like to check if a top level JavaScript function exists from Dart, before calling it through JS interop. I thought exposing the typeof JS operator somehow would help, but could not get it work.
Things I have tried.
Using package:js:
@JS()
library existence_check;
import 'package:js/js.dart';
@JS()
external void someJsFunction(String input);
@JS()
external String typeof(object);
String check() => typeof(someJsFunction);
Calling check() will give me the following exception (testing in Chrome):
NoSuchMethodError: method not found: 'typeof' (self.typeof is not a function)
Using dart:js:
import 'dart:js';
String check() => context.callMethod('typeof', [42]);
I get the exception:
NullError: method not found: 'apply' on null
Wrapping the interop function call in a try-catch block:
@JS()
external void someJsFunction(String input);
try {
someJsFunction('hi');
} on NoSuchMethodError {
// someJsFunction does not exist as a top level function
} catch(e) {
if (e.toString() == 'property is not a function') {
// We are in Dartium and someJsFunction does not exist as a top level function
} else {
rethrow;
}
}
I assume the first two approaches did not work because typeof is not a function, but an operator. The third approach works, but notice how I had to prepare for different exceptions based on the current browser. And I'm not sure it will work across all platforms, all browsers.
Is there any better way to check for the existence of a JS function before calling it?