简体   繁体   中英

Work with javascript from iframe

I have a script:

$(document).ready(function(){
    $('#submit').click(function(e){
        window.location.href = '/dash/do/record/' + $('#filename').val()
        return false;
    });
});

written as <script src="...jquery..."></script> and <script>... the code </script>

If I load it right from the browser, it works, but if it is called through an iframe, not. What's the reason? What should I do? (The main page has the jquery tag, too)

You are trying to redirect the iframe to a new site. Most likely your browser is protecting you from Cross Site Scripting. I tried to replicate your results by redirecting my iFrame to Google. My console subsequently popped an error and now reads the following:

Refused to display 'https://www.google.ca/?gfe_rd=cr&ei=EAiWU_TDMKuC8QfC4YG4DA&gws_rd=ssl' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

You can still redirect the parent by using :

window.top.location.href = '/dash/do/record/' + $('#filename').$

Or redirect the iframe itself with:

window.top.$('iframe')[0].src = "" 

see if you are executing this script from an iframe which is a child window then you have to use parent :

window.parent.location.href = "";

want to redirect the iframe, not the whole page.

Then you can create a function on parent page to change the src of the iframe :

on parent page:

function changeSrc(url){
   $('iframe').attr('src', url);
}

on iframe document:

$(document).ready(function(){
   $('#submit').click(function(e){
      window.parent.changeSrc('/dash/do/record/' + $('#filename').val());
      return false;
   });
});

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