简体   繁体   English

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

[英]How can you run code in the event of a Javascript EventListener NOT firing?

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). 我有一个页面(我们将其称为父页面),其中包含一个内嵌框架,其中包含另一个页面的内容(我们将其称为子页面)。

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. 我正在使用window.postMessage在两个页面之间进行通信。 I've successfully sent a message to the child page from the parent page and the child page has successfully sent a message back. 我已经从父页面成功地向子页面发送了消息,并且子页面已经成功地将消息发送回了。

I am using eventListeners on both pages to listen for the message. 我在两个页面上都使用eventListeners来侦听消息。 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. 我的意图是,如果父母在一定时间内没有收到消息,则应该更改位置并加载默认页面。

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? 还是有另一种方法可以实现我没有想到的目标?

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM