Содержимое файла может быть прочитано только в глобальную переменную, а не в свойство объекта - PullRequest
0 голосов
/ 27 сентября 2019

Я создаю веб-расширение, в котором я хотел бы прочитать файл, назначить его свойству объекта и затем использовать содержимое файла позже.Мне удалось назначить содержимое файла глобальной переменной, но всякий раз, когда я назначаю его объектной переменной, он теряется, как только выполнение программы прекращается функцией загрузки.

Я создал простое расширение, в котором я могувоспроизведите проблему.

manifest.json

{

  "manifest_version": 2,
  "name": "FilePickFail",
  "version": "1.0.1",

  "description": "File content loaded to object property is lost after getting out of scope FileReader onload function.",

  "icons": {
    "48": "icons/fit-tagger-48.png"
  },

  "browser_action": {
    "default_icon": "icons/fit-tagger-48.png",
    "theme_icons": [{
        "light": "icons/fit-tagger-48.png",
        "dark": "icons/fit-tagger-48.png",
        "size": 48
    }]
  },

  "sidebar_action": {
    "default_title": "Fit-tagger",
    "default_panel": "popup/main-menu.html"
  },

  "content_scripts": [
    {
      "matches": ["*://*.facebook.com/groups/1127391613999255*"],
      "js": ["filereader.js", "content_scripts/content.js"]
    }
  ],


  "permissions": [
    "<all_urls>",
    "activeTab",
    "tabs",
    "storage"
  ]

}

filereader.js

function savePasswdPath(request, sender, sendResponse) {
    console.log("I have received something");
    console.log(request);
    browser.storage.local.set({"filePicked" : request.passwdFile});
}

browser.runtime.onMessage.addListener(savePasswdPath);

var fileContent = "";

class FileManager {
    constructor() {
        this._fileContent = "";
    }

    async readPasswd() {
        var getFile = browser.storage.local.get();

        getFile.then(results => {
            console.log("Local storage contents:");
            console.log(results);

            var fileToRead = results["filePicked"];
            console.log(fileToRead);

            if (fileToRead) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    this._fileContent = e.target.result;
                    console.log("File content:");
                    console.log(this._fileContent);

                    fileContent = e.target.result;
                };

                reader.readAsText(fileToRead);
            }
            else {
                console.log("FILE NOT LOADED")
            }
        });
    }
}


var fileManager = new FileManager();
fileManager.readPasswd();

function timeoutCallback() {
    console.log("fileManager");
    console.log(fileManager);
    console.log("file content variable");
    console.log(fileContent);
}

setTimeout(timeoutCallback, 3000);

popup / main-menu.html

<!DOCTYPE html>

<html>

  <head>
    <meta charset="utf-8">
    <!-- <link rel="stylesheet" href="main-menu.css"/> -->
  </head>

  <body>

    <div id="picker_zone" style="margin:20px ;color:blue">
      <span>Load text file: </span>
      <input type="file" id="input">
    </div>

    <script src="main-menu.js"></script>

  </body>

</html>

popup / main-menu.js

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handlePicked, false);

function handlePicked() {
    var file = this.files[0];
    if (!file) {
        return;
    }
    saveFile(this.files);
}

function saveFile(fileList) {
    const file = fileList[0];
    browser.tabs.executeScript({
            file: "/content_scripts/content.js"
        }).then(messageContent)
        .catch(reportError);

    function messageContent() {
        const gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
        gettingActiveTab.then((tabs) => {
            browser.tabs.sendMessage(tabs[0].id, {file});
        });
    }

    function reportError(error) {
        console.error(`Could not inject content script: ${error}`);
    }
}

content_scripts / content.js

(function() {
  /*
  Check and set a global guard variable.
  If this content script is injected into the same page again,
  it will do nothing next time.
  */
  if (window.hasRun) {
    return;
  }
  window.hasRun = true;

  function saveFile(request, sender, sendResponse) {
    console.log("I have received something");
    console.log(request);

    browser.storage.local.set({"filePicked" : request.file});
  }

  browser.runtime.onMessage.addListener(saveFile);
})();
...