元标记和 javascript 浏览器重定向 - 哪个优先?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15956405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:44:03  来源:igfitidea点击:

Meta tag and javascript browser redirection - which has priority?

javascriptredirectcurlmeta-tags

提问by Michael B

I'm developing in PHP, using Curl to follow links to their final destination. I occasionally reach a page with a meta tag redirection or a javascript redirection, and want to be smart enough to follow them. If a page has both, which should I follow (i.e., which would fire first)?

我正在用 PHP 进行开发,使用 Curl 跟踪指向其最终目的地的链接。我偶尔会访问一个带有元标记重定向或 javascript 重定向的页面,并希望足够聪明地跟随它们。如果一个页面同时具有,我应该遵循哪个(即,哪个会先触发)?

Sample meta tag refresh:

元标记刷新示例:

<meta http-equiv="refresh" content="0;URL='http://location1.com/'">

Sample javascript refresh:

示例 javascript 刷新:

<script>
window.location.href='http://location2.com/';
</script>

回答by Nick Andriopoulos

Just created this file ( let's call it test.html)

刚刚创建了这个文件(让我们称之为test.html

<html>
  <head>
    <meta http-equiv="refresh" content="0;URL='http://location1.com/'">
    <script type="text/javascript">
      window.location.href='http://location2.com/';
    </script>
  </head>
  <body>
    Hello
  </body>
</html>

You can copy and save it. Once you open it, you'll be directed to http://location2.com

您可以复制并保存它。打开后,你会被引导到http://location2.com

Do note that if the <script>tag is not in the <head>tag, the <meta>tag gets executed first.

请注意,如果<script>标签不在<head>标签中,则<meta>首先执行标签。

回答by Ryan M

Hexblot's answer is a good idea -- just try it out if you want to see what happens. However, when I did try it out, Chrome went to location2, and IE went to location1. So it seems to be implementation dependent. You might want to have this be a configurable option on your script. In practice, though, any site that has one redirect in a meta tag and a different one in a script, is (a) unlikely, and (b) not coded very well, as they have no idea where you'll end up.

Hexblot 的答案是个好主意——如果你想看看会发生什么,就试试吧。但是,当我确实尝试时,Chrome 转到了 location2,而 IE 转到了 location1。所以它似乎取决于实现。您可能希望将其作为脚本中的可配置选项。然而,在实践中,任何在元标记中具有一个重定向而在脚本中具有不同重定向的站点都是 (a) 不太可能的,并且 (b) 编码得不是很好,因为他们不知道你最终会在哪里。

回答by jgillich

I don't think there is a good way to detect which one would fire first.

我不认为有什么好方法可以检测哪个先开火。

The meta tag has the contentattribute which can be used to specify a timeout. However, in JavaScript it is nearly impossible to detect when the redirect will happen as there are infinite ways to write it. At least not without executing it. Example:

元标记具有content可用于指定超时的属性。然而,在 JavaScript 中几乎不可能检测到重定向何时发生,因为有无数种方法可以编写它。至少在不执行它的情况下不会。例子:

var t = 100;
setTimeout(function () {
    window.location.href='http://location2.com/';
}, t * 2);