import 'dart:js_interop'; import 'package:web/web.dart' as web; import '../domain/artifact_html_links.dart'; /// The iframe's sandbox: no script, no same-origin access, no forms and no /// navigation of the app, but a link may open a new tab that is itself /// unsandboxed (an ordinary website, as if typed into the address bar). const String artifactHtmlSandbox = 'allow-popups allow-popups-to-escape-sandbox'; /// [html] with every link's behaviour fixed before the frame shows it /// ([artifactHtmlLinkAction]): a `#place` stays in the frame and scrolls /// there, an http(s)/mailto address opens a new tab (no opener, no /// referrer), and every other link loses its `href`, so it is inert text. /// A document's own `` is dropped: the frame is not at the artifact's /// address, and a relative link must not reach the app's origin. /// /// The browser's `DOMParser` builds an inert document: nothing in it runs or /// loads while it is rewritten. String artifactHtmlWithInertLinks(String html) { final doc = web.DOMParser().parseFromString(html.toJS, 'text/html'); final bases = doc.querySelectorAll('base'); for (var i = bases.length - 1; i >= 0; i--) { (bases.item(i) as web.Element?)?.remove(); } final links = doc.querySelectorAll('a[href], area[href]'); for (var i = 0; i < links.length; i++) { final link = links.item(i) as web.Element?; if (link == null) continue; final href = link.getAttribute('href') ?? ''; switch (artifactHtmlLinkAction(href)) { case ArtifactHtmlLinkAction.inDocument: // A srcdoc document's base is the app page, so a bare `#place` would // navigate the frame to the app; the document's own address keeps it // a same-document jump. final hash = href.indexOf('#'); final place = hash < 0 ? '' : href.substring(hash); link.setAttribute('href', 'about:srcdoc$place'); link.setAttribute('target', '_self'); case ArtifactHtmlLinkAction.external: link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); case ArtifactHtmlLinkAction.blocked: link.removeAttribute('href'); link.removeAttribute('target'); } } final doctype = doc.doctype == null ? '' : ''; return '$doctype${doc.documentElement?.outerHTML ?? ''}'; }