使用JavaScript在浏览器中打开文件时写入文件

时间:2014-02-17 21:04:27

标签: javascript html file-io

我想知道JavaScript是否能够写入浏览器中打开的文件。我正在开发一个链接页面,链接到我自己使用的一些关键网站(为了好玩,而不是必需)。目前我正在尝试开发一些用户可以在文本框中键入链接和名称并将链接保存到HTML文件本身的内容。使用JavaScript将链接和名称添加到页面显然很容易,但是一旦会话到期,当再次访问页面时,将不会添加链接。我想这样做,因为我不想每次想要添加新链接时都找到并加载文件。使用PHP和MySQL很容易实现,但是这个文件没有在服务器上运行。

总而言之,一旦文件被当前会话修改,是否可以保存文件?

我的代码如下:

<!DOCTYPE html>
<html>
<head>
    <script type = "text/javascript">
        function add(link,name)
        {
            htmlstring = "<a href='"+link+"'>"+name+"</a>";
            document.getElementById('urlsdiv').innerHTML += htmlstring;
        }
    </script>
</head>
<body>
    <input type = "button" onclick = "validate(document.getElementById('validbox').value)" value = "check">
    <div id = "urlsdiv">
        <input type = "text" id = "addbox">//Box to type new URL
        <input type = "text" id = "addname">//Box to type link name
        <input type = "button" onclick = "add(document.getElementById('addbox').value,document.getElementById('addname').value)" value = "Add">//Add new link to page
        <a href = "https://www.facebook.com">Facebook</a>//These three links
        <a href = "http://www.youtube.com">YouTube</a>//have already been hard-coded
        <a href = "https://mail.google.com">Gmail</a>//into the file
    </div>
</body>
</html> 

1 个答案:

答案 0 :(得分:2)

浏览器中的 位于安全沙箱中,并且无法访问HTML5 File API允许其访问的包含区域之外的文件系统。目前,support is very limited,即使是那些API。

请注意,我在浏览器中区分了JavaScript,因为native JavaScript的较新实现,例如NodeJS