如果Javascript EventListener未触发,如何运行代码?

时间:2021-08-24 16:03:22

I have a page (we'll call it the parent page) that contains an iframe with another page's content in it (we'll call it the child page).

我有一个页面(我们称之为父页面),其中包含一个iframe,其中包含另一个页面的内容(我们将其称为子页面)。

The 2 pages are hosted on different domains.

这两个页面托管在不同的域上。

If the child page does not load, I want to change the location of the child page to a default page.

如果子页面未加载,我想将子页面的位置更改为默认页面。

I am using window.postMessage to communicate between the 2 pages. I've successfully sent a message to the child page from the parent page and the child page has successfully sent a message back.

我使用window.postMessage在2页之间进行通信。我已成功从父页面向子页面发送消息,并且子页面已成功发回消息。

I am using eventListeners on both pages to listen for the message. My intent is that if the parent does not receive a message back within a certain timeframe, it should change the location and load the default page.

我在两个页面上都使用eventListeners来监听消息。我的意图是,如果父级在特定时间范围内没有收到回复消息,则应更改位置并加载默认页面。

Is there a way to run a function if the parent page's eventListener is NOT triggered in a certain amount of time?

如果在一定时间内未触发父页面的eventListener,是否有办法运行函数?

Or is there another way to accomplish the goal that I'm not thinking of?

还是有另一种方法来实现我没想到的目标?

1 个解决方案

#1


0  

You could do something like the following:

您可以执行以下操作:

var onNoEvent = setTimeout(function(){
  //... do your thing
}, 3000);

window.addEventListener('message', function(){
  clearTimeout(onNoEvent); //cancel the timeout event

}, false);

#1


0  

You could do something like the following:

您可以执行以下操作:

var onNoEvent = setTimeout(function(){
  //... do your thing
}, 3000);

window.addEventListener('message', function(){
  clearTimeout(onNoEvent); //cancel the timeout event

}, false);