繁体   English   中英

检测iframe的不活动状态

[英]Detect inactivity with iframe

我创建了一个网站,该网站在iframe中显示了three.js模型。 每当用户闲置x分钟后,我都会尝试将其重定向回首页(index.html)。 我已经将其与某些Java脚本一起使用,但是问题是,仅当我在iframe之外处于活动状态时,它才起作用。 当我实际旋转模型并与之交互时,它仍然会重定向我。 我一直在对此进行研究,但尚未找到解决方案。 我试着用以下命令在iframe中调用该函数

onload="setup();"

但这不起作用,还有许多其他问题。 这是我的代码,

Javscript

var timeoutID;

        function setup() {
            this.addEventListener("mousemove", resetTimer, false);
            this.addEventListener("mousedown", resetTimer, false);
            this.addEventListener("mouseover", resetTimer, false);
            this.addEventListener("mouseout", resetTimer, false);
            this.addEventListener("keypress", resetTimer, false);
            this.addEventListener("DOMMouseScroll", resetTimer, false);
            this.addEventListener("mousewheel", resetTimer, false);
            this.addEventListener("touchmove", resetTimer, false);
            this.addEventListener("MSPointerMove", resetTimer, false);

            startTimer();
        }

        function startTimer() {
            // wait 5 seconds before calling goInactive
            timeoutID = window.setTimeout(goInactive, 5000);
        }

        function resetTimer(e) {
            window.clearTimeout(timeoutID);

            goActive();
        }

        function goInactive() {
            // do something
            window.location = "index.html";
        }

        function goActive() {
            // do something

            startTimer();
        }

HTML

<main role="main" class="col-md-9 ml-sm-auto col-lg-12 px-0">

            <!-- Featured Content  -->

              <div class="embed-responsive embed-responsive-16by9">
                  <div id="test">

                      <iframe style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none;
                   margin:0; padding:0; overflow:hidden; z-index:0;" class="embed-responsive-item" src="models/model.html" onload="setup();" allowfullscreen></iframe>
                  </div>

              </div>

        </main>

事件不会在iframe的“障碍”中冒出。 我不确定您的用例是什么,但是使用iframe似乎并不是实现此目的的最佳方法。

但是,如果有必要,那么我建议您侦听iframe内容何时已加载iframe.onload事件(或为load添加事件侦听器),然后在iframe.contentWindow添加必要的click事件(您可以如果脚本来自同一来源,则只能访问)。

const frame = document.createElement('iframe');
document.body.appendChild(frame);
frame.addEventListener('load', function() {

  frame.contentWindow.addEventListener("mousemove", resetTimer, false);
  frame.contentWindow.addEventListener("mousedown", resetTimer, false);
  //..other events...

});

// ...
frame.src = ".../file.html";

暂无
暂无

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

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