【问题标题】:How do I make a chrome app write to a file如何让 Chrome 应用程序写入文件
【发布时间】:2014-02-13 10:46:09
【问题描述】:

我刚开始学习 chrome 应用程序,我对它的 javascript 方面还很陌生,但我确实对它的 HTML 方面有一些经验。如何创建一个具有复选框的应用程序(复选框将是 html),然后有一个按钮(也都在 html 中),并且无论复选框是否被选中,此按钮都会写入我桌面上的文件未经检查?即它会写真或假?

【问题讨论】:

  • 你的问题太宽泛了。您不是在问一个可以轻松回答的问题,因为“我如何创建应用程序......?”问题意味着您希望有人为您编写代码。请写一些代码,如果它不起作用,请返回并发布另一个问题。
  • 我确实想要某种通用代码,因为我对 chrome 应用程序的真实情况一无所知。但是由于我的问题有点广泛,只问初学者,我如何获得一个我在 html 中创建的按钮来执行一个简单的操作,例如打开一个网页,这可能是因为诸如“”之类的内联代码不是允许吗?而且我不知道这将如何与 javascript 一起使用...

标签: javascript html google-chrome google-chrome-app


【解决方案1】:

保存到文件并不像听起来那么容易。我建议检查 Chrome 应用程序示例 (found here),加载扩展程序并查看哪个可以满足您的需求。然后你去检查代码。最适合您的示例是 mini-code-edit 示例,它同时具有加载文件和保存到文件的功能。

不过,如果你不这样做,这个示例代码应该可以工作:

//Selector for your "Save" button
document.querySelector("#saveButton").onclick = saveToFile;
//Save variables
var fileEntry;
var hasWriteAccess;
//Save methods
function saveToFile()
{
    if (fileEntry && hasWriteAccess) {
    writeEditorToFile(fileEntry);
    } else {
        chrome.fileSystem.chooseEntry({ type: 'saveFile', suggestedName: "suggestedFileName.txt"}, onChosenFileToSave);
    }
}

function setFile(theFileEntry, isWritable) {
  fileEntry = theFileEntry;
  hasWriteAccess = isWritable;
}

function writeEditorToFile(theFileEntry) {
  theFileEntry.createWriter(function(fileWriter) {
    fileWriter.onerror = function(e) {
      console.log("Write failed: " + e.toString());
    };

    var blob = new Blob(["You put whatever you want written to your file here."]);
    fileWriter.truncate(blob.size);
    fileWriter.onwriteend = function() {
      fileWriter.onwriteend = function(e) {
        //handleDocumentChange(theFileEntry.fullPath);
        console.log("Write completed.");
      };

      fileWriter.write(blob);
    }
  }, errorHandler);
}

var onChosenFileToSave = function(theFileEntry) {
  setFile(theFileEntry, true);
  writeEditorToFile(theFileEntry);
};

这取自我提到的示例。另外,请记住将 "fileSystem": ["write"] 添加到您的清单中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 2021-01-22
    • 2016-03-20
    相关资源
    最近更新 更多