I am using an iframe in order to isolate its content's CSS. Which is working great. But, I need the iframe to load an external script, specifically the script I am loading is: https://web.squarecdn.com/v1/square.js
You can see that this external script calls document
often. I need it to reference the document of my iframe not the document of the parent HTML.
I have tried this and it does not accomplish this:
const insertScriptToIframe = (doc, target, src, callback) => {
var s = doc.createElement("script");
s.type = "text/javascript";
if(callback) {
if (s.readyState){ //IE
s.onreadystatechange = function(){
if (s.readyState == "loaded" ||
s.readyState == "complete"){
s.onreadystatechange = null;
callback();
}
};
} else { //Others
s.onload = function(){
callback();
};
}
}
s.src = src;
target.appendChild(s);
}
// add web payments script
const createWebPaymentsNode = () => {
const iFrame = document.createElement('iframe');
const context = iFrame.contentDocument;
const frameHead = context.getElementsByTagName('head').item(0);
insertScriptToIframe(context, frameHead, 'https://web.squarecdn.com/v1/square.js');
}
It adds the external script to the iframe. But the external script is referencing the parent document. I know it is doing this because the external script, itself, loads other scripts and iframes that are being placed in the parent HTML, instead of the iframe's.
I need to be able to do this in vanilla js. Thank you