Search code examples
darthtml5-fullscreen

How to request fullscreen in compiled dart


I'm playing around with a Dart app trying to get fullscreen mode to work. My HTML (excluding boilerplate):

<div id="fullscreen_div">
  Clicking this should cause it to go fullscreen!
</div>

My Dart code:

import 'dart:html';

void main() {
  var div = querySelector('#fullscreen_div');
  div.onClick.listen((MouseEvent e) {
    div.requestFullscreen();
    print('requested fullscreen');
  });
}

Here it is on DartPad.

If I've done this correctly, clicking the div once should cause the div to go into fullscreen mode. On Chromium, this works. When compiled to JavaScript (both debug and minified), this does not happen, and the console outputs:

Uncaught TypeError: undefined is not a function

This happens on both Chrome, Firefox and IE (tested on Windows 7). From what I've understood this is a common JavaScript error, and searching does not bring up anything obvious.

Any ideas why requestFullScreen won't work when dart is compiled to JS?


Solution

  • As pointed out in the comments (thanks Günter!), this is a known issue. #12 in that thread posted a good workaround, edited by me to be a bit more generic:

    import 'dart:js';
    void fullscreenWorkaround(Element element) {
      var elem = new JsObject.fromBrowserObject(element);
    
      if (elem.hasProperty("requestFullscreen")) {
        elem.callMethod("requestFullscreen");
      }
      else {
        List<String> vendors = ['moz', 'webkit', 'ms', 'o'];
        for (String vendor in vendors) {
          String vendorFullscreen = "${vendor}RequestFullscreen";
          if (vendor == 'moz') {
            vendorFullscreen = "${vendor}RequestFullScreen";
          }
          if (elem.hasProperty(vendorFullscreen)) {
            elem.callMethod(vendorFullscreen);
            return;
          }
        }
      }
    }
    

    I used this in my code, and replaced this call

    div.requestFullscreen();
    

    with

    fullscreenWorkaround(div);
    

    which worked great. Tested and working compiled on Chrome and IE.