Greasy Fork is available in English.

Discussions » Development

Settings export-import

§
Posted: 03/04/2021

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.

§
Posted: 03/04/2021

solutions that don't involve GM functions

Local storage

§
Posted: 03/04/2021

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

§
Posted: 03/04/2021

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
      }
    };
  }
§
Posted: 03/04/2021

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

Post reply

Sign in to post a reply.