web
web copied to clipboard
Add helpers to make it easier to use trusted types
I think HTMLScriptElement needs a src setter that accepts a TrustedScriptURL.
After conditionally creating a trustedUrl like this:
// If TrustedTypes are available, prepare a trusted URL.
web.TrustedScriptURL? trustedUrl;
if ((web.window as JSObject).hasProperty('trustedTypes'.toJS).toDart) {
// create a TrustedTypePolicy `policy` object
trustedUrl = policy.createScriptURL(_url, null);
}
I'm finding myself doing this:
final web.HTMLScriptElement script =
// ignore: avoid_dynamic_calls
(web.document.createElement('script') as dynamic
// ignore: unsafe_html
..src = (trustedUrl ?? _url)
..async = true
..defer = true) as web.HTMLScriptElement;
Docs:
- https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API
- See "Injection Sinks": Setters for Element attributes that accept a URL of code to load or execute.
- https://developer.mozilla.org/en-US/docs/Web/API/TrustedScriptURL
(Another way would be to pass trustedUrl.toString(), but that kind of defeats the purpose of TrustedScriptURLs, and would still flag me as unsafe_html I think :/)
Thanks for filing the issue - I like the alternative you did in https://github.com/flutter/packages/pull/5581/files#diff-fef182cc76f54d7074aee070ced4ddd44ad9233ebf438472221dc834f5f342d9 where you added an extra setter with the right type. The workaround using dynamic relies on using the dart:html interceptor, and if one day we remove it (which we hope we do in the future), it would stop working.
Yes, the workaround with dynamic felt very iffy, and it triggered a bunch of unsafe_html lints :) Being able to rename the setter was nice!
I'm generalizing this issue a bit more to address some other use cases I'm seeing like checking whether trustedTypes is available, and the ability to not pass anything for args in createScriptURL.
Trusted Types with the latest syntax has landed #173 again, but it still needs tweaks to be usable. I've created #175 so we don't forget :)
I wonder if we should be able to flag certain top-level..."things" as optional so the generator can understand them...
TrustedTypes is one of the most egregious examples, though:
- https://caniuse.com/mdn-api_trustedtypes
I'm not aware of any other non-prefixed chrome-only "top level" APIs like this!