I run the page:

<html> <head> <title>Frames</title> <link rel="shortcut icon" href=""> </head> <body> <p>Два фрейма</p> <iframe src="a.html" name="A"></iframe> <iframe src="b.html" name="B"></iframe> </body> </html> 

It has two frames, respectively.

Frame "A":

 <html> <head> <title>A Frame</title> </head> <body> <p>Фрейм A</p> <a href='#1'>f2</a> <script> var f2 = parent.Bf; var aTag = document.getElementsByTagName('a'); aTag[0].addEventListener('click', f2, false); </script> </body> </html> 

and frame "B":

 <html> <head> <title>B Frame</title> </head> <body> <p>Фрейм B</p> <a href='#2'>f</a> <p id='res'></p> <script> var x = 10; var y = 11; var xy = 0; var resHtml = document.getElementById('res'); function f(){ resHtml.innerHTML = xy; xy = x + y; x++; y++; return xy; } var aTag = document.getElementsByTagName('a'); aTag[0].addEventListener('click', f, false); </script> </body> </html> 

The idea is that when you click on a link located in frame "A",

 <a href='#1'>f2</a> 

the click event should fire and start the function that is in frame "B". However, this event does not work every time. When reloading the page may or may not work.

The click event in frame "B" is stable.

Who faced a similar problem? Why event triggered "through time"?

  • Tell me, who silently minus questions? What does not suit you? The text of the question is literate, all the required code is given, minimum efforts are required for reproduction. Good question. - Igor

1 answer 1

It is quite simple. Frames pages are loaded in random order. In some cases, during the execution of the code in A, the page in B has already loaded, and the function f in it already exists. And in some - no.

Use:

 <p>Фрейм A</p> <a href='#1'>f2</a> <script> var f2 = function () { return parent.Bf(); }; var aTag = document.getElementsByTagName('a'); aTag[0].addEventListener('click', f2, false); </script> 

Update

Just a minute, you don’t call f2() yourself. String in your code

 var f2 = return parent.Bf; 

sets f2 to undefined if the page has not yet loaded in B, and then this undefined is sent to addEventListener , where it is simply ignored.

In case of

 var f2 = function () { return parent.Bf(); }; 

the call to the function f from the page of frame B, occurs when the user clicks the link - by this time both pages have long been loaded. And in addEventListener we addEventListener function defined here in page A.

  • Igor, if you can, another question, in the case when page B did not load, why does f2 () not return undefined? - Oleg Sukhikh
  • @ OlegSuhih Added in response. - Igor
  • great solution to the problem. I tried to solve it by re-reloading Frame A, noting that by manually reloading it, I got the desired result. I did not know about the "random download". - Oleg Sukhih