0

So, what this option should do is let the user upload a file (an image) with <input id="background-image" type=file></input> (this works) but how do I get the background image to stay when a user opens a new tab or closes the current tab.

Here is the JS that sets the background image:

document.getElementById('background-image').addEventListener('change', readURL, true);
function readURL(){
   var file = document.getElementById("background-image").files[0];
   var reader = new FileReader();
   var readFile = reader.readAsDataURL(file);
   reader.onloadend = function(){
     document.getElementById("main-background-image").style.backgroundImage = "url(" + reader.result + ")";        
   }

   if(file){
      reader.readAsDataURL(file);
    }else{
    }
} 

Again this sets the image for the current tab, as long as the user doesn't click away. Is it possible to keep the user's background image for future and other tabs ?

  • Simply save reader.result in chrome.storage.local (asynchronous) or localStorage (synchronous). – wOxxOm Jun 07 '18 at 13:09
  • Sorry to ask, but I am not sure where I would assign the reader.results in the if statement or somewhere else? To assign the reader.result, would it be something like ` localStorage["background-image"] = reader.result;` . – Dimitriy Kruglikov Jun 07 '18 at 13:28

1 Answers1

0

My solution was based on another stackoverflow question: Saving an uploaded image to localStorage (chrome extension)

var input = document.getElementById('getval');
    input.onchange = function(evt){
        var tgt = evt.target || window.event.srcElement, 
            files = tgt.files;

        if (FileReader && files && files.length) {
            var fr = new FileReader();
            fr.onload = function () {
                localStorage['foo'] = fr.result;
            }
            fr.readAsDataURL(files[0]);
        }
    }

after I inserted this bit of code:

window.onload=function(){
var el = document.querySelector('body');
el.style.backgroundImage = 'url(' + localStorage['foo'] + ')';