I've written a bookmarklet (with a little help from the experts at Stackexchange) and I've run into a small little issue where I can't close the thing.
Here's the code (sensitive people should probably move on):
javascript: (function () {
var htmlheader = "<html><head></head>"
var html = htmlheader + "<body><a href='javascript:document.getElementById(\"TroubleiFrame\").style.visibility = \"hidden\"'>Close</a>" +
"</body></html>";
var iframe = document.createElement('iframe');
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
iframe.style.background = "#fff";
iframe.style.width = "50%";
iframe.style.height = "500px";
iframe.style.left = "25%";
iframe.style.top = "25vh";
iframe.style.position = "fixed";
iframe.style.zIndex = "9999";
iframe.id = "TroubleiFrame";
iframe.style.boxShadow = "0 0 0 100vw rgba(0,0,0,0.75)";
document.body.appendChild(iframe);
})();
When clicking on the close link I get this error:
Uncaught TypeError: Cannot read property 'style' of null
If I paste the command in Chromes console it works:
document.getElementById("TroubleiFrame").style.visibility = "hidden"
Do you have any ideas on what I'm doing wrong? If possible I'd love a brief explanation too so I'm learning something from it.
/Patrik
Your
iFrame
doesn't know about an element called "TroubleiFrame" since it is in a child window.You need to call the parent instead, and from there you can close it
Look at this question to see how to close the iFrame properly. Right now you're just going to hide it