简体   繁体   中英

how to change iframe src from inside it

I need to change src attribute of iframe after click a button inside the iframe.

<button type="button" onclick="ch_src('page2.php')">Submit</button>

<script type='text/javascript'>
function ch_src(loc) 
{ 
var v = document.getElementById('iframe1');
v.src = loc;
}
</script>

(1) when using window.location = loc; it changes the content of iframe but src still pointing to previous page.
(2) why we need to change src value not only open the new page inside iframe? we use JS to print iframe content excluding content outside iframe. this script is printing page in src not actual opened page.
(3) above function can't change src mostly coz it can't get element id of itself (iframe) but may be sub elements.
(4) when moving the function outside the iframe, it doesn't execute. may be due to "same origin policy"

finally we need to click a button in (page1.php) inside iframe causes
(1) load (page2.php) into same iframe
(2) change iframe's src attribute to (page2.php)

first include jquery then try this in you page1.php:

<script type="text/javascript">
$(document).ready(function(){
  $("iframe").load(function(){
      $(this).contents().find("button").click(function(){
      document.querySelectorAll("iframe").src = "https://example.com/page2.php";
      });
  });
});
</script>

for better detection please paste your page1.php here

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