Create and close iframe in bookmarklet

556 views Asked by At

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

2

There are 2 answers

2
Rene Pot On

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

parent.document.getElementById("TroubleiFrame");

Look at this question to see how to close the iFrame properly. Right now you're just going to hide it

0
Rafael Araújo On

I've also came across this problem creating a bookmarklet just like Pinterest's Pin It.

It should work cross-domain.

The only way I could work this out, was by posting events between the page inside the iframe and the parent page following this example on GitHub:

https://gist.github.com/kn0ll/1020251

I've posted an answer on this other thread: https://stackoverflow.com/a/43030280/3958617

And also found one more example on this other thread: https://stackoverflow.com/a/21882581/3958617

Hope it helps!