1

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?

3
  • 1
    Try hasOwnProperty() Commented Feb 13, 2018 at 9:37
  • Great idea! Exposing and calling window.hasOwnProperty() works. It will not tell me if it's a callable function, but for simple existence check this is good. Care to add as an answer? Commented Feb 13, 2018 at 10:19
  • Glad about that :) Added as answer Commented Feb 13, 2018 at 11:27

1 Answer 1

2

Use hasOwnProperty()

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

from MDN webdocs Object.prototype.hasOwnProperty()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.