DylanPiercey/set-dom

HTML parsing fails randomly on iOS UIWebView

Closed this issue · 5 comments

When running our site in a iOS UIWebView, it happens pretty often that html parsing throws a null is not an object (evaluating doc.body.firstChild) exception.

I have unfortunately been unable to create a self-contained example to reproduce it, but it's an issue affecting our users (caught by TrackJS) and that I could reproduce quite consistently in our environment.

I debugged this further and here's what I found: at times (quite rarely, but prominent when using set-dom a lot), DOMParser.parseFromString will return a document, but doc.body is not available until the next tick, even for a simple markup (like <div></div>).

I tried the following:

  • parse again when doc.body is not available. Does not fix
  • recreate a new parser = DOMParser() and reparse when doc.body is not available. Does not fix
  • add some random html at the end of the markup (in case it's some caching optimization). Does not fix

The only solution I found is to call the fallback function (innerHTML-based), only when doc.body is null, since we can't detect this consistently prior to setting up the parseHTML function

I will open a PR shortly. I'd understand if you'd rather not merge this since it's quite a major change on parse-html and it fixes a hard-to-isolate bug, but did not want to not contribute back again :)

Thank you very much for taking the time to isolate and resolve this issue. I won’t be able to take a solid look at the changes for probably a week or two since I am in the process of moving and switching jobs.

I look forward to digging into this and testing myself and hope to merge a good solution as soon as possible.

Sounds good @DylanPiercey, we pushed a similar patch to our production environment, so we'll know soon if that addresses the issue in full
Good luck with moving and switching jobs!

Great, please let me know how that goes. I had a chance to review the PR (no time to test though) and it looks pretty good.

One concern I have that may not be addressable is avoiding a double parse in the iOS webview. Ideally there would be a way to detect this browser inconsistency during initialization but it may not be possible.

Thanks again for taking the time to put together the PR and dig into this.

Update: we've not seen this error happening since then, so that's good news

Fwiw, the double parse would only happen in the very rare cases where the first parse fails to return synchronously. I tried to find a way to consistently force the failure without success (as it's been pretty random from the start)

Thanks for the update, sorry for the delay.