How to check if a method is available in document or window?

122 views
Skip to first unread message

KwangYul Seo

unread,
Nov 25, 2015, 2:45:34 AM11/25/15
to mi...@dartlang.org
Hello.

In JavaScript, we can check if a method is avaialble by simply checking if it is undefined.

```
var hasCaretPositionFromPoint = document.caretPositionFromPoint != undefined;
```

In Dart, this trick does not work because a function defined using JS annotation is never null. For example, `caretPositionFromPoint` defined below is a normal closure even if the browser does not provide caretPositionFromPoint. Calling it certainly throws an error because the method is not acatually avaialble.

```
@JS('CaretPosition')
class CaretPosition {
  Node offsetNode;
  int offset;
}

@JS('document.caretPositionFromPoint')
external CaretPosition caretPositionFromPoint(num x, num y);

void main() {
  print(caretPositionFromPoint != null); // always print true;
  caretPositionFromPoint(0, 0); // throws an error
}
```

Is it possible to query if a method is available in document or window using only Dart code? If yes, what's the most conventional way to achieve this?

Thanks,
Kwang Yul Seo


Tyler James Thompson

unread,
Nov 25, 2015, 2:58:25 AM11/25/15
to mi...@dartlang.org

This is a shot in the dark but can't you check the runtype of what you are calling and if you don't want that then you could just assert for that value? I can double check tomorrow or sometime when I'm at a computer

print(document.caretPositionFromPoint.runType)

--
For other discussions, see https://groups.google.com/a/dartlang.org/
 
For HOWTO questions, visit http://stackoverflow.com/tags/dart
 
To file a bug report or feature request, go to http://www.dartbug.com/new
---
You received this message because you are subscribed to the Google Groups "Dart Misc" group.
To unsubscribe from this group and stop receiving emails from it, send an email to misc+uns...@dartlang.org.

KwangYul Seo

unread,
Nov 25, 2015, 3:32:06 AM11/25/15
to mi...@dartlang.org
Querying runtimeType does not work as it always returns undefined regardless of the existence of the underlying method.


Matthew Butler

unread,
Dec 5, 2015, 3:38:28 PM12/5/15
to Dart Misc
Keep in mind that the dart:html it's api from blink directly. As such the api documented will be available to dart. However api which may not exist in say Firefox, will often have some type of isSupoorted Property.
Similarly if it's in Firefox, but not Blink, then it can't be directly accessed from dart. There may be a way to accomplish that through js interop but I've never tried.

Matthew Butler

unread,
Dec 5, 2015, 3:45:25 PM12/5/15
to Dart Misc
Sorry on mobile. To follow up on this specific case, dart should either try to polyfill or add a supportsCaretPositionFromPoint property. I'd suggest filling a bug
Reply all
Reply to author
Forward
0 new messages