I found a monkey-patching way: make a global variable: window.iframeDoc.
// Get the iframe element
var iframe = document.evaluate("/html[1]/body[1]/iframe[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
// Access the iframe's document object
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
// make iframeDoc global
window.iframeDoc = iframeDoc;
// later when other scripts not sure whether to use document or iframeDoc
var startDoc = document;
if (window.iframeDoc) {
startDoc = window.iframeDoc;
}
var e2 = startDoc.evaluate("id('shadow_host')", startDoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
console.log(`e2=${e2}`);
The result
e2=[object HTMLDivElement]
It works for the purpose. Welcome to point out any drawback with it. Thank you