dart-lang / web

Lightweight browser API bindings built around JS static interop.
https://pub.dev/packages/web
BSD 3-Clause "New" or "Revised" License
135 stars 23 forks source link

problems setting element style attributes in firefox #275

Closed muth02446 closed 3 months ago

muth02446 commented 3 months ago

This simple function works on chrome but not on firefox

void show_flex(web.HTMLElement element) {
  _log('show ${element.runtimeType}');
  element.attributeStyleMap.set('display', 'flex'.toJS);
  _log('after show');
}

one firefox, the developer console shows: `` Uncaught : TypeError: null: type 'JSNull' is not a subtype of type 'JSObject' wrapException js_helper.dart:1190 _failedAsCheck rti.dart:1388 _generalAsCheckImplementation rti.dart:1366 SwitchToTab$1 js_util_patch.dart:81 SwitchToTabAndPushState$1 main.dart:177 main main.dart:188 $protected main.dart.js:4196 call$2 async_patch.dart:328 _asyncStartSync async_patch.dart:233 main main.dart:538

srujzs commented 3 months ago

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/attributeStyleMap#browser_compatibility

Firefox doesn't support attributeStyleMap. The cast from undefined to JSObject then fails. If you want to query whether the element supports that member, you can use has from dart:js_interop_unsafe (the library says unsafe, but as long as you use a constant string for the property, it's fine). Another alternative is to define a nullable extension member for attributeStyleMap e.g.

extension on web.HTMLElement {
  @JS('attributeStyleMap')
  external StylePropertyMap? get nullableAttributeStyleMap;
}
robertmuth commented 3 months ago

so what is the recommended way of setting style.display?

Also, would it make sense to just remove attributeStyleMap from the bindings (or somehow make it read-only) to prevent people like myself from writing code that breaks on a mainstream browser -- assuming there is a more portable alternative.

robertmuth commented 3 months ago

Maybe I got confused by the documentation. In https://pub.dev/documentation/web/latest/web/HTMLElement/style.html it say element.style is read-only but apparently it is possible mutate the object itself. I thought I tried that and got some compiler complaints - will try again.

srujzs commented 3 months ago

Also, would it make sense to just remove attributeStyleMap from the bindings (or somehow make it read-only) to prevent people like myself from writing code that breaks on a mainstream browser -- assuming there is a more portable alternative.

We initially tried removing APIs that don't work on all mainstream browsers, but this removes really useful Chrome-specific APIs like trusted types so we opted against it. We've discussed emitting possible support annotations to instruct users that an API might not work on some browsers which could address this gap.