簡體   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