Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

61
Views
A text is displayed only right after my javascript is triggered

I wrote javascript codes.

By clicking the button, the child window pops up and displays a text sent from the parent window using a postMessage function.

My code could sent a text to the child window, but there's no text displayed. The text is displayed only when I keep clicking the button. I don't want the text to disappear.

I think my code is overridden by a blank script or something, though I don't write any other codes except for below.

Do you have any solution for this?

the parent window html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Parent Window</title>
</head>
<body>
  <input type="button" value="TEST_BUTTON" id="testButton">

  <script>
      var testButton = document.getElementById('testButton');
      testButton.addEventListener('click', function(event) {
        event.preventDefault();
        var newWindow = window.open('./child_window.html', 'popupWindow', 'width=400,height=300');
        newWindow.postMessage('this is a content from the parent window.', '*');
        return false;
      },false);
  </script>
</body>
</html>

the child window html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Pop Up Window</title>
  </head>
  <body>
    <h1 id="mainText"></h1>
    <script type="text/javascript">
      var mainText = document.getElementById('mainText');

      window.addEventListener('message', function(event) {
        console.log(event.data);
        this.mainText.innerText = event.data;
      }, false)
    </script>
  </body>
</html>
7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

I ended this up using localStorage instead.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.