reacting to changes on html cell

I’d love to be able to define some worker code in a cell with these kinds of contents

<script id="workerCode">
   function main() {
    let result =[{x:5}]
    return result
  }
  onmessage = function(oEvent) {
    postMessage(main(oEvent.data));
  };
</script>

And then have changes to that cells contents go on to trigger executions of other cells that make a worker with that script as src, and exchange messages with the worker.
This is possible if I create a named js cell containing either a string representation of source or html templated script with contents, but I lose the syntax highlighting, and auto formatting .

workerSrc = html`<script id="workerCode">
   function main() {
    let result =[{x:5}]
    return result
  }
  onmessage = function(oEvent) {
    postMessage(main(oEvent.data));
  };
</script>`

Is there a way to make a notebook sensitive to changes in the contents of an html cell?

You cannot add script tags this way (see this explanation). Instead you’ll have to turn your code into an object URL:

workerUrl = URL.createObjectURL(
  new Blob([codeAsString], {type: 'text/javascript'})
)

You may also find @Fil’s Worker notebook helpful.

As for watching for changes:

  1. Note that you can assign names to HTML cells via the cell toolbar at the bottom that is visible while you edit the cell. That way you can reference an HTML cell directly, so that your dependent cell can rerun when the cell is invalidated.
  2. If the HTML only changes internally, consider using viewof to expose a value that other cells can reference and depend on. Have a look at this notebook for a short explanation.
  3. If you still must watch for arbitrary DOM changes, you can use a MutationObserver.
3 Likes