繁体   English   中英

JavaScript、HTML:“window.location.replace then alert”无法正常工作

[英]JavaScript, HTML : “window.location.replace then alert” not working in order

我正在构建一个在特定时间运行 JavaScript 函数的网页。 该函数应将网页移动到about:blank页面并提醒网页已过期。 我得到要在我想要的时间执行的函数,但该函数执行警报部分,然后移动页面。 如果 alert 在window.location.replace之前弹出,用户仍然可以看到网页。 我希望网页先移动到about:blank页面,然后提醒用户该网页已过期。 以下是我的代码。

<SCRIPT>
    function checkExpiry() {
        var now_ = new Date();
        var expiry = new Date("<?php echo $expiry ?>")
        if (now_ > expiry) {
            window.location.replace("about:blank");
            alert("The webpage is expired.");
        }            
    }
    setInterval(function () { checkExpiry(); }, 15 * 1000);
</SCRIPT>

该功能每 15 秒正常运行一次,但在更换位置之前会发出警报。 如果用户没有点击警报中的“确定”按钮,他仍然可以看到网页。 我希望网页移动到about:blank页面,然后弹出警报。 任何建议表示赞赏!

一方面,您无法打开about:blank并在此之后运行自定义 JS,并且通常在更改window.location后您无法运行代码(并且由于事件循环的设置方式,更改后的一些代码语句被执行)。

您可以在您的网站上创建一个自定义/expired页面,在加载自定义空白页面时运行alert(" ... ")

还要记住,有些人禁用了 JavaScript,并且可以通过用户脚本覆盖window.location.replace所做的事情。

另一种选择(仍然可以被用户脚本覆盖,但一切都可以)是删除网页上的所有内容:

<SCRIPT>
    function checkExpiry() {
        var now_ = new Date();
        var expiry = new Date("<?php echo $expiry ?>")
        if (now_ > expiry) {
            document.body.innerHTML = "";
            document.head.innerHTML = "";
            setTimeout(() => alert("The webpage is expired."), 0); // force alert() to the end of the callstack so body & head get cleared before alert
        }            
    }
    setInterval(function () { checkExpiry(); }, 15 * 1000);
</SCRIPT>

这是运行的示例(检查开发工具以查看它全部消失):

 function expire() { document.body.innerHTML = ""; document.head.innerHTML = ""; setTimeout(() => alert("The webpage is expired."), 0); }
 <h1>This is a webpage</h1> <p>not really, but you get the point</p> <button onclick="expire()">run "expire" function manually</button> <p>check dev tools (inside the iframe) after expiring to see that this is all gone</p>

你想要的是不可能的,因为你不能在另一个任意网页上运行代码。 如果您希望页面为空白,则解决方法是将<body>的不透明度设置为 0

<script>
    function checkExpiry() {
        let now = new Date();
        let expiry = new Date("<?php echo $expiry ?>")
        if (now > expiry) {
            document.body.style.opacity = 0
            alert("The webpage is expired.");
        }            
    }
    setInterval(function () { checkExpiry(); }, 15 * 1000);
</script>


暂无
暂无

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

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