我能否使用JavaScript停止meta refresh?

13
以下代码允许用户停止元刷新的发生 - 它成功地从页面中移除了,但浏览器仍然会刷新页面。 有什么办法可以使它工作吗?
<!doctype html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8" />
<meta http-equiv="refresh" content="5" id="refresh" />
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(function(){
  $("a").click(function(e){
    e.preventDefault();
    $("#refresh").remove();
  });
});
</script>
</head>
<body>

Reloaded at <span id="time"></span>
<script>
document.getElementById("time").innerHTML = Date();
</script> 

<a href="#">Stop refresh</a>


</body>
</html>

编辑:这与此问题不同,因为该问题希望为不支持JavaScript的用户提供备用解决方案-而我的情况并非如此(该问题的大多数答案不适用于此问题)。


无法更改,元标记已在页面加载时解析,之后对其进行的任何更改都将被忽略。 - Teemu
我对你的问题没有答案,但我可以问一下为什么首先要使用meta refresh? - aaronk6
一个旁注:http://www.w3.org/TR/WCAG10-CORE-TECHS/#auto-page-refresh - Mörre
1
我找到了一个巧妙的答案:https://dev59.com/T3A75IYBdhLWcg3wg5Zh#13656851 - unarist
一些关于该问题的答案似乎只是“停止元刷新的发生”,即使该问题与您的情况不匹配。 - unarist
4个回答

17

仅为完整性而提供,不是我的建议方式。你可以调用:

window.stop();
停止加载窗口。Internet Explorer不支持此功能,您需要执行以下操作:
document.execCommand("Stop");

出于调试目的,这对我非常有帮助。谢谢! - Shane N

4

我认为你无法做到这一点,因为在页面加载时读取标题并且浏览器将安排刷新。我不认为浏览器会给你一个取消的方法,因为它实际上是HTTP头,而不是文档的一部分。最好为body元素添加一个onload处理程序,使用定时器安排刷新,然后让您的单击处理程序取消计时器。

<script type="text/javascript">
$(function(){
  var timer;

  $('body').on('load', function() {
      timer = setTimeout(refresh, 5000);
  });

  $("a").click(function(e){
    e.preventDefault();
    if (timer) {
       clearTimeout(timer);
       timer = null;
    }
  });

  function refresh() {
      timer = null;
      document.location.reload(true);
  }
});
</script>

我将 var timer 放在了 $(function(){ 外面,并移除了 $('body').on('load', function() {});。然后就好了! - regisls

3

这对我非常有效!(在Chrome中尝试)

<button onclick="pauseshow()"><img id="myImg" src="images/pause.jpg" width="45" height="45" style="position:absolute; top:10px; left:1200px;" ></button>
function pauseshow()
{
    window.stop();
    //  Below did not work --> 
    //  var mr = document.getElementById("mymetatag");
    //  mr.parentNode.removeChild(mr);

}

1

由于页面加载时重新加载已经触发,因此您无法通过JavaScript稍后删除标题。但是可以延迟5秒。

相反,您可以改变思路,使用JavaScript重新加载页面而不是使用meta标签:

<!doctype html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8" />
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
var timer = setTimeout(function() {
  window.location = window.location;
}, 5000);
$(function(){
  $("a").click(function(e){
    e.preventDefault();
    clearTimeout(timer);
  });
});
</script>
</head>
<body>

Reloaded at <span id="time"></span>
<script>
document.getElementById("time").innerHTML = Date();
</script> 

<a href="#">Stop refresh</a>


</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接