简体   繁体   English

使用iframe中的javascript

[英]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> 写成<script src="...jquery..."></script><script>... the code </script>

If I load it right from the browser, it works, but if it is called through an iframe, not. 如果我从浏览器加载它,它可以工作,但如果它是通过iframe调用,而不是。 What's the reason? 什么原因? What should I do? 我该怎么办? (The main page has the jquery tag, too) (主页面也有jquery标签)

You are trying to redirect the iframe to a new site. 您正尝试将iframe重定向到新网站。 Most likely your browser is protecting you from Cross Site Scripting. 您的浏览器很可能会保护您免受Cross Site Scripting的攻击。 I tried to replicate your results by redirecting my iFrame to Google. 我尝试通过将iFrame重定向到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: 或者重定向iframe本身:

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 : 看看你是否从一个iframe作为子窗口执行这个脚本,那么你必须使用parent

window.parent.location.href = "";

want to redirect the iframe, not the whole page. 想要重定向iframe,而不是整个页面。

Then you can create a function on parent page to change the src of the iframe : 然后,您可以在父页面上创建一个函数来更改iframesrc

on parent page: 在父页面上:

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

on iframe document: 在iframe文档:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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