javascript - 使用 iframe 检测不活动
问题描述
我创建了一个网站,在 iframe 中显示了一个 three.js 模型。每当用户处于非活动状态 x 分钟时,我都会尝试将用户重定向回主页(index.html)。我已经让它与一些 java 脚本一起工作,但问题是它只在我在 iframe 之外处于活动状态时才有效。当我实际旋转模型并与之交互时,它仍然会重定向我。我一直在研究这个并没有找到解决方案。我试过用 iframe 调用函数
onload="setup();"
但这并没有奏效,还有很多其他的。这是我的代码,
Javascript
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
(只有在脚本来自同一来源)。
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";
推荐阅读
- android - 如何使 Theme.Holo 适应 App 主题?
- sql - 返回取决于数字的行数
- hdfs - 如何使用 hdfs dfs cp 和 xargs 来解决 linux 参数列表限制?
- c# - 使用 NetOffice 创建 PDF/A 文件
- javascript - 如何在 VueJS 3 中使用 9.0.1 Firebase 方法
- c++ - 照片的C++ DLL注入
- java - 如何缩放PNG图像直到达到目标文件大小
- android - Android 中的 Splash Activity 未设置为全屏活动 - 三星 M51
- google-cloud-platform - 在 GCP 上部署 2-NIC 的独立 BIG-IP
- postgresql - 使用 libpq (postgresql) 进行高效的行读取