【问题标题】:URL be truncated if it contains '#' in chrome如果 URL 在 chrome 中包含“#”,则 URL 将被截断
【发布时间】:2015-12-16 15:22:48
【问题描述】:

假设如下进行http get请求:

var url = "https://ss1.bdstatic.com/k4oTfnSm1A5BphGlnYG/newmusic/happy.png";
var img = new Image();
img.src = url + '?hello=world|a=1|href=#feedback';

在chrome(47.0)中,请求url为https://ss1.bdstatic.com/k4oTfnSm1A5BphGlnYG/newmusic/happy.png?hello=world|a=1|href=

丢失#feedback

在 Firefox(42) 中,请求 url 是https://ss1.bdstatic.com/k4oTfnSm1A5BphGlnYG/newmusic/happy.png?hello=world|a=1|href=#feedback

为什么 chrome 会截断 url?

【问题讨论】:

  • 简单地对参数进行urlencode,#用于在页面内锚定
  • 但是 Firefox 工作正常。
  • 它是一个不合格的网址。

标签: javascript google-chrome url


【解决方案1】:

您的 URL 是一个有效的 URL,但它并不代表您的想法。

如果正确解析,您的网址如下:

scheme = https
authority = ss1.bdstatic.com
path = k4oTfnSm1A5BphGlnYG/newmusic/happy.png
Query = hello=world|a=1|href=
fragment = feedback

如果你想让你的Query为hello=world|a=1|href=#feedback,你必须编码#,否则会被理解为Query的结束和Fragment的开始。

对它进行编码,您的 URL 将如下所示:

https://ss1.bdstatic.com/k4oTfnSm1A5BphGlnYG/newmusic/happy.png?hello=world|a=1|href=%23feedback

如果您想在 Javascript 中对其进行编码,请使用 encodeURIComponent

var url = "https://ss1.bdstatic.com/k4oTfnSm1A5BphGlnYG/newmusic/happy.png";
var img = new Image();
img.src = url + '?hello=world|a=1|href=' + encodeURIComponent('#feedback');

之所以出现差异,可能是因为RFC 2616 没有说 URL 可以在 HTTP 请求中包含 fragment,因此 Chrome 决定它们不能拥有,而 Firefox 将其作为查询部分的一部分。

【讨论】:

  • 感谢您花时间扩展我的评论,写得很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多