Javascript 解决IE下location.href不识别base路径

阅读(3063)

为解决同一个用户同时操作多个账户的场景时,一般会采取 http://kaifage.com/ACCOUNT_ID/ 的形式,以不同的path区分操作账户,同时对应的cookie(如果需要)也能按照path隔离。此时,带来的问题便是链接间的跳转。

考虑一个场景:访问页面 http://kaifage.com/10000/order/create,此时要跳转到 order/list 页面,期望中的做法是location.href='order/list'。那对页面增加一个base标签就可以解决:

<base href="/10000/" />

问题来了:在IE下,location之后的地址不符合预期,变成了错误的“http://kaifage.com/10000/order/order/list”。解决方法为使用 location.assign

location.assign('order/list')

有人解释这个问题的原因是Netscape和IE标准的差异:

This is a long-standing difference going back to the early days of Netscape-vs-IE.

IE enforces base-href only at the point a document element is interacted-with. So, you can createElement('a'), set a relative href and click() it*, but the base-href will be ignored; appendChild it to the document containing the base-href, and it'll work.
On the other browsers the base-href is taken as global per-window and always applied.

via:http://stackoverflow.com/questions/632471/base-href-javascript-and-internet-explorer-vs-firefox

ps: 有人评论提到的IE8可能还有问题未实测,如果应用场景涉及需要测一下。

Tags: