I have a Java Script code that works inside Iframe. I’d like to save the Iframe context so that my next script can work in the same context.
The following is my code
// Get the iframe element
const iframe = document.evaluate("/html[1]/body[1]/iframe[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
// Access the iframe's document object
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
// use iframe doc directly
var e1 = iframeDoc.evaluate("id('shadow_host')", iframeDoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
console.log(`e1=${e1}`);
// can I assign iframeDoc to document?
document = iframeDoc;
var e2 = document.evaluate("id('shadow_host')", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
console.log(`e2=${e2}`);
I got the following result
e1=[object HTMLDivElement]
e2=null
Looks like if I use Iframe doc directly, I able able to search inside the Iframe context. I did this with e1.
But If I assign the Iframe doc to ‘document” variable, I am not able to search inside the Iframe context. I did this with e2.
Why my e2 example doesn’t work?
I really wanted to use ‘document’ variable because it is global and I don’t have to pass a variable to my next call.
Thank you for any help