简体   繁体   中英

Close iframe modal with button

I am using the following to load an iframe from a bookmarklet:

javascript:(function(d){
var%20modal=document.createElement('iframe');
modal.setAttribute('src','http://myurl.com/page.html?url=
'+encodeURIComponent(window.location.href)+'&
page_title='+document.title);
modal.setAttribute('scrolling','no');
modal.className='modal';
document.body.appendChild(modal);
var c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='//myurl.com/css/wl_iframe.css';
document.body.appendChild(c);
}(document));

and to close it I am trying:

<button onclick="parent.$.iframe.close();">X Close Window</button>

I've also tried:

<button onclick="modal.$.iframe.close();">X Close Window</button>

But they are not working, they do nothing.

I know I can use:

<a href="underneath url" target="_parent">X Close Window</a>

But this then causes a the browser to re-refresh the page they were looking at and also the user has to press the back button twice to get to the page before which is not ideal.

Any ideas?

you should add some name or id to your iframe

javascript:(function(d){
var modal=document.createElement('iframe');
modal.setAttribute('src','http://myurl.com/page.html?url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);
modal.setAttribute('scrolling','no');

modal.setAttribute('name', 'my_modal_window');

modal.className='modal';
document.body.appendChild(modal);
var c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='//myurl.com/css/wl_iframe.css';
document.body.appendChild(c);
}(document));

And then

<a href="#" onclick="var modals = document.getElementsByName('my_modal_window'), i = modals.length; while(i--){ modals[i].parentNode.removeChild(modals[i])}">X close window</a>

EDIT working solution, have just tested on stackoverflow inside Chrome JS console:

(function(d){
var modal=document.createElement('iframe');
modal.setAttribute('src','http://myurl.com/page.html?url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);
modal.setAttribute('scrolling','no');

modal.setAttribute('name', 'my_modal_window');

modal.className='modal';
document.body.appendChild(modal);
var c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='/css/wl_iframe.css';
document.body.appendChild(c);

var a = document.createElement('a');
a.onclick= function(){
   var modals = document.getElementsByName('my_modal_window'),i = modals.length;
   while (i--) {
      modals[i].parentNode.removeChild(modals[i]);
   }
};
a.innerHTML = 'Close Iframes';
document.body.appendChild(a);
}(document))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM