未捕获的TypeError:无法读取undefined的属性'chooseEntry'(使用fileSystem API开发chrome扩展时)

时间:2018-05-02 14:38:35

标签: javascript html google-chrome google-chrome-extension google-chrome-devtools

我正在使用chrome的fileSystem API开发chrome扩展,需要以.txt格式保存文件。我有以下代码 -

manifest.json -

{
    "version": "1.0",
    "manifest_version": 2, 
    "permissions": [{"fileSystem": ["write", "retainEntries", "directory"]}],
    "background": {
        "scripts": ["js/background.js"],
        "persistent": false
    },
    "content_scripts": [
       {
        "matches": ["file:///index.html"],
        "css": ["css/style.css"],
        "js": ["js/app.js"]
       }
    ]
}

app.js -

(function () {
    var text = document.getElementById("content").innerHTML;
    var saveAsButton = document.getElementById("saveas");
    function errorHandler() {
        return null;
    }
    saveAsButton.addEventListener('click', function(e) {
        chrome.fileSystem.chooseEntry({type: 'saveFile'}, function(writableFileEntry) {  
            writableFileEntry.createWriter(function(writer) {
                writer.onerror = errorHandler;
                writer.onwriteend = function(e) {
                    console.log('write complete');
                };
                writer.write(new Blob([text], {type: 'text/plain'}));    
            }, errorHandler);   
        }); 
    });
})();

index.html -

<html>
    <head>
        <title>note-in-chrome</title>
        <link rel="stylesheet" href="css/style.css"/>
    </head>
    <body>
        <button id="saveas">SAVE AS</button>
        <div id="content" contenteditable="true" data-text="Enter text here"></div>
        <script src="js/app.js"></script>   
    </body>
</html> 

每当我点击SAVE AS按钮时,都会打开选择文件的提示,但我收到以下错误 - Uncaught TypeError: Cannot read property 'chooseEntry' of undefined

1 个答案:

答案 0 :(得分:3)

chrome.fileSystem API适用于Chrome apps,但不适用于Chrome extensions