user3144310
user3144310

Reputation:

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)

Upvotes: 1

Views: 85

Answers (2)

Monarch Wadia
Monarch Wadia

Reputation: 4956

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 = "" 

Upvotes: 2

Jai
Jai

Reputation: 74738

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;
   });
});

Upvotes: 1

Related Questions