For anyone looking for a quick copy-paste answer: include a color-scheme meta header in the injected iframe. It must match the color-scheme header of the web page, if one exists. Do not add the meta header if a website does not have one. As this requires programmatic effort to figure out if such header exists a what the content value is, those steps are omitted, but once the scheme is known, the injection code would look something like this:
document.body.insertAdjacentHTML(
'afterbegin',
'<iframe style="background: red" srcdoc="' +
'<meta name=\'color-scheme\' content=\'light dark\'>' +
'<style>body {background:none}">')
Next a more detailed answer, and how I discovered it.
The screenshots show macOS in dark mode. If you go to OS settings and toggle the appearance between light and dark, this should alternate the white color and red color behind the iframe. Try and see if this happens.
After some experimentation, I discovered iff a website has a meta header for color-scheme:
<meta name="color-scheme" content="light dark">
as is the case with Github.com and sjmulder.nl, an iframe without matching header is only able to handle light mode correctly, and renders a white background if user device is set to prefer dark mode. I suspect this is because "major browsers default to light mode if not otherwise configured".
You can experiment with this and switch the color mode header on a test website to "light" (only) and "dark" (only) without specifying anything in the injected iframe; or define it in the iframe and not on the website, then switch the device color mode preference to see the effect. The conclusion I reached was the headers must match for iframe background color to get applied correctly.
I reached a strange Chrome limitation on some websites
When a website has not defined a color-scheme meta header and the injected iframe has not defined one either, there is no mismatch, and there is no issue, which is why this problems only presents on some websites. I also tried other browsers (Edge, Opera) and they have this same issue, at least on macOS. But it can be fixed in an extension by first checking if there exists a meta header on the page, and if yes, applying that same header to the injected iframe.