Open justinfagnani opened 2 months ago
To implement this we need a component to show console messages, but we also need to hook the preview iframe to forward those messages.
I've been prototyping this and think this is the rough shape of a solution:
window.console
. This is necessary because it's not possible to patch the console from outside of the iframe[^1]destination
field of Request in the service worker fetch event handler. Values of iframe
and document
(for when the preview is loaded in a tab outside of the iframe) tell us when to add the script.<script>
tags before <html>
work just fine. This avoids actually parsing the HTML.postMessage()
[^2]. Some objects can't be structure cloned, so they'll have to be toString()
on the sending side. If we want to support logging DOM objects, we'll need to serialize them specially.message
event listener.console
events on their project.[^1]: Even when the iframe is same-origin to its parent, the parent cannot patch the new global object created from a navigation (src = ...
) before the scripts from that document run. This means it isn't possible to intercept console calls in top-level module statements.
[^2]: We could use Comlink to send the messages. That would probably look like changing the serviceWorkerAPI.setFileAPI
approach to take a ProjectAPI object that can retrieve files or receive console messages. I'll try this out, since proxying DOM objects might be useful if it works.
It would be very useful to be able to view preview console output in the playground, instead of having to have users open up their browser's console and sift or filter to find the right logs. It'd be especially useful for code examples where you just want to show that something happened without wiring up the output to an HTML UI.