简体   繁体   English

如何在Chrome上的javascript中读取客户端上的本地txt文件?

[英]How to read local txt file on a client side in javascript on chrome?

I need to be able to read settings text file in a Chrome extension, but without asking user to set path to this file. 我需要能够读取Chrome扩展程序中的设置文本文件,但无需要求用户设置该文件的路径。

I've tried the following but XMLHttpRequest() doesn't work with file:///path/to/file.txt URL's in Chrome. 我尝试了以下操作,但XMLHttpRequest()不适用于Chrome中的file:///path/to/file.txt URL。

var x = new XMLHttpRequest(); 
x.open("GET","logins.txt",false); 
x.send(); 
myTextFile=x.responseText; 

How to do that? 怎么做?

This works here. 这在这里有效。 Note that I'm using asynchronous request. 请注意,我正在使用异步请求。

Files: 文件:

ls /path/to/extension/
background.js main.html manifest.json sample.txt test.js

manifest.json: manifest.json的:

{
    "name"          : "TEST XMLHttpRequest Local File",
    "version"       : "0.0.0.1",
    "manifest_version"  : 2,
    "minimum_chrome_version": "23",
    "app": {
        "background": {
            "scripts": [
                "background.js"
            ]
        }
    }
}

background.js: background.js:

chrome.app.runtime.onLaunched.addListener(function() {
    chrome.app.window.create('main.html', {
        bounds: {
            width   : 200,
            height  : 300,
            left    : 100,
            top     : 100
        },
        minWidth    : 200,
        minHeight   : 300
    });
});

main.html: main.html中:

<html>
  <head>
    <title>TXT GET</title>
  </head>
  <body>
    <button id="btn">Get file</button>
    <pre id="log"></pre>
    <script type="text/javascript" src="test.js"></script>
  </body>
</html>

test.js: test.js:

var btn = document.getElementById('btn');
var log = document.getElementById('log');

function xhttpResponse() {
    log.innerHTML += this.responseText;
}

btn.addEventListener('click', function() {
    var x;

    log.innerHTML = "Get file " + (+new Date());
    x = new XMLHttpRequest();
    x.onload = xhttpResponse;
    x.open("GET", "sample.txt", true);
    x.send();
    log.innerHTML += "\n\n------ REQ SENT ------\n\n";
});

sample.txt: sample.txt的:

Lorem ipsum

Result: 结果:

[_Get file_]

Get file 1392378751700

------ REQ SENT ------

Lorem ipsum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM