Go to local URL with Javascript

喜夏-厌秋 提交于 2019-11-26 06:44:00

问题


Same question as here but I need to go to local URL\'s in Firefox

I tried with code like

var url = \"file:///E:/Test/Test.htm\";
window.location.href = url;

but id didn\'t work. Tried to go with window.location = url; and also tried with url = \"file://E:/Test/Test.htm\"; (double \"/\" instead of triple \"/\") and still doesn\'t work.

Thanks


回答1:


When I try this:

window.location.href = "file:///C:/Users/Cerbrus/Documents/SomeFile.js"

(Yes, it is a valid path.)

Chrome throws me this error:

Not allowed to load local resource: file:///C:/Users//Documents/File.js

This is because JavaScript does not have access to local files (due to it being sandboxed), and you're setting the new url with JavaScript.
"SandBoxed" means a technology has restricted (or no) access outside a certain set of bounds. In the case of browsers, this means that the code that runs on the page can not access files on your system (Otherwise, it would be easy to "steal" data, by just having a look at the user's file system).

However,

Say, I have 2 files:

C:/Test/Test.htm
C:/Test/Test1.htm

Test.htm contains only this:

<script>
    window.location = "file:///C:/Test/Test1.htm";
</script>

This will actually redirect to Test1.htm, since the target file is on the same domain as where the source file's from.




回答2:


I guess its not allowed to load local resource from javascript

Unless you have a local http server running:

var url = "http://localhost/MySite/Default.aspx";
window.location.href = url;

It will work




回答3:


You cannot access the file from the local system. Since the Browser works in the sandbox mode and you cannot breach the sandbox and reach the local file system since it would violate the security. Either try to directly load using an AJAX request else what you are trying to do is not possible due to sandbox restrictions and also does not comply with the security policies.




回答4:


window.location.href = window.location.pathname + (your local file name or path)




回答5:


window.open(url); // here url can be anything


来源:https://stackoverflow.com/questions/14052473/go-to-local-url-with-javascript

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