Greasy Fork is available in English.

게시판 » 개발

Settings export-import

§
작성: 2021-04-03

Does anybody tried to make export-import of script settings? If yes, can you share base ideas behind your implementation?
I'd prefer solutions that don't involve GM functions.

§
작성: 2021-04-03

solutions that don't involve GM functions

Local storage

§
작성: 2021-04-03

Local storage is for storing settings inside browser. I'm asking about exporting from browser to, say, file and then importing back.

§
작성: 2021-04-03

I use this function to export the script settings:

  function downFile(fileName, fileContent) {
    let elementA = document.createElement("a");
    elementA.setAttribute(
      "href",
      "data:text/plain;charset=utf-8," + encodeURIComponent(JSON.stringify(fileContent))
    );
    elementA.setAttribute("download", fileName);
    elementA.style.display = "none";
    document.body.appendChild(elementA);
    elementA.click();
    document.body.removeChild(elementA);
  }

/* example */
downFile('BLTH_CONFIG.json', exportJson);

Then import the setting like this:

// html
<button data-action="importConfig" class="igiftMsg_btn">import setting</button>
<input type="file" id="BLTH_config_file" style="display:none"> /* file button */

//js 
const inputConfig = $("#BLTH_config_file"); 
inputConfig.on("change", importConfig);
/* When user click this button, trigger the invisible file button.
 * I do it in this way because the file button is too ugly.
*/

  function importConfig() {
    let selectedFile = document.getElementById("BLTH_config_file").files[0];
    let reader = new FileReader();
    reader.readAsText(selectedFile);
    reader.onload = function () {
      console.log("importConfig:", this.result);
      try {
        // some code
      } catch (e) {
        // handle error
      }
    };
  }
§
작성: 2021-04-03

@andywang, thanx. I took your idea as baseline.

댓글 남기기

댓글을 남기려면 로그인하세요.