HTMRewriter API : Adding script attribute based on text of the script tag


Is it possible to add a script attribute after processing the content text inside the script tag with HTML Rewriter API?

[](Sample Playground Code)

I am adding a sample code which I have written so far with some random string check for script body and adding script attribute based on that check. But this doesn’t seem to work,

This content token is no longer valid. Content tokens are only valid during the execution of the relevant content handler.
    at addNonce (worker.js:40)
    at ElementHandler.text (worker.js:30

Currently I am using regex (which is a lot heavier operation) to extract the script body and add attributes to script tag. If HTML ReWriter API works for my use case then it will improve the performance of my worker manyfolds.

No, once you see the text, element is already queued for output. You can not “go back” and fix atrributes.

If script element is not nested you could try marking all script elements as removed and reading them again before seing another element as previous sibling. I am not sure this will give any value, may be too much work.

Other option is to buffer all output and do replacement after, but it will probably be slower than your current regex based solution.

1 Like

And you may run out of RAM in production, always do distributed load-testing to check for this behavior.