Search code examples
javascriptgoogle-chromeiframeparentinnerhtml

Changing the innerhtml on another page does not work in Chrome (they are in the same domain)


I have build a website with an iframe to display multiple subpages. My goal is to change the value of an ID on the parent window, from the child page that is loaded in the Iframe. All the pages are in the same domain. I am currently using the following code, and it works fine in Internet explorer, but doesn't do anything in Chrome? I hope someone will have the awnser to fix it so it will work in all browsers. Thank you in advance!

Here's the html of the parent window:

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Webpage</title>
  <base target="iframe">

  <!-- External Javascript -->
  <script src="javascript/index.js"></script>

  <!-- External CSS -->
  <link rel="stylesheet" href="css/index.css">

</head>

<body>

  <!-- Banner -->
  <div class="Banner">

    <div id="Site-name">
      Text to be changed
    </div>
    <img class="Logo" src="Afbeeldingen/Logo.png" alt="logo">

  </div>

  <!-- Body -->

  <div class="iframe">
    <iframe name="iframe" src="iframe.html"></iframe>
  </div>

  <!-- Footer -->
  <div class="Footer">
    <div class="copyright">
      Made by Jan Pieter van den Oever 2019 All rights reserved ®
    </div>

  </div>

</body>

</html>

And here is the java script of the index file:

function changeText(text) {
  document.getElementById('Site-name').innerHTML = text;
}

Here is the iframe html:

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>iframe</title>

  <!-- CSS -->
  <link rel="stylesheet" href="css/iframe.css">

</head>

<body>

  <div class="Button-container">
    <div class="Button-center">
      <div class="Button" onclick="location.href='nextpage.html';parent.changeText('The new text to be displayed in the parent')">
        <div class="Button-text">
          <br><br><br>
          Start
        </div>
      </div>
    </div>
  </div>

</body>

</html>

Solution

  • With jQuery:

    function changeText(newText) {
    
    $('#Site-name').text(newText)
    
    }
    

    Just include jQuery in your project and replace the changeText function with the above one. If the above code doesn't work, try the below one:

    function changeText(newText) {
    
    $(document).find('#Site-name').text(newText);
    
    }