HTML5 push/replaceState and the <base> tag causes security exception

房东的猫 提交于 2019-12-22 04:25:09

问题


I have a test version of a site located at a subdomain of the normal site, like: http://test.x.com instead of http://x.com.

I use the <base> tag to translate all resource requests back to the original domain:

<base href="http://x.com/" />

This tactic worked great until I implemented HTML5 push/replaceState support.

Now, if I execute this statement in the console:

history.pushState({}, "", "");

... then I get a DOMException object in WebKit-based browsers:

code: 18
constructor: DOMExceptionConstructor
line: 2
message: "SECURITY_ERR: DOM Exception 18"
name: "SECURITY_ERR"
sourceId: 4839191928
__proto__: DOMExceptionPrototype

... and this error in FireFox 4:

Security error" code: "1000

If I remove the <base> tag and execute the same statement, the new state is pushed, and there's no exception.

A few questions: 1) is this behavior a security risk, or is it a bug? And 2) is there a workaround to prevent the exception, or a tactic other than using the <base> tag that will sidestep the issue completely?

Thanks for your consideration.


回答1:


It is not a bug, you are violating the Same origin policy. "" is a relative URL which will be resolved to 'http://x.com/' since you used the <base> tag. http://x.com is a different domain from where the page is hosted which is why doing this runs afoul of the same origin policy.

Using an absolute URL that points to a resource on http://test.x.com/ in your history.pushState() call should fix this:

history.pushState({}, "", "http://test.x.com/");


来源:https://stackoverflow.com/questions/6351447/html5-push-replacestate-and-the-base-tag-causes-security-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!