DenaliHardtail DenaliHardtail - 3 months ago 9
Javascript Question

Why is my callback function undefined?

I have a page defined as follows:

<body>
<div id="container">
<p>
<input id="myButton" type=button onclick=window.open('LandingPage.html'); value="Launch Search App">
</p>
</div>
<script>
function cb(msg) { console.log(msg); }
myButton.addEventListener('click', cb);
</script>
</body>


This page is responsible for setting up a callback function for a secondary page. The callback function seems to be setup, at least according to F12 Developer Tools where I see a
PointerEventPrototype
created. The
PointerEventPrototype
is not present if I comment out the line containing the
addEventListener()
that sets up the callback so I believe I have it working so far.

Clicking the button on the first page launches another window containing the second page, shown below:

<body>
<div id="container">
<p>
<input type=button value="Save" onclick="click_function()">
</p>
</div>
<script>
function click_function() {
var message = "Save button clicked!";

console.log(message);
cb(message);
}
</script>
</body>


The second page contains a Save button that is intended to respond to the callback function setup on the first page. When the Save button is clicked, "Save button clicked!" is output to the console but the following line,
cb(message)
, throws an error that says
cb
is undefined. How can this be undefined? Do I need to call the callback function using a different syntax?

Answer

cb exists only in the first page. If they're on the same origin, your second page can refer to the global window of the first page via its opener global, so:

opener.cb(message);

That only works because cb is a global on the first page, so it's a property of the window object.

Having said that, though, it may be a cleaner design to use web messaging, and it comes with the benefit that it will work cross-origin as well. Rather than having one page reach out and call a function in another, with web messaging you post a message to the page and let it handle the message however it sees fit. There's a complete, simple example in my answer here.

Comments