Search code examples
javascriptpng

Store a png file inside a javascript variable?


I am making a chrome extension that will show you a button, and when you click on it a picture of a puppy randomly selected from a database, I'm trying to figure out how to store a png file in a js variable. A little help?


Solution

  • You can simply store a url location of the image and then set the variable like this.

    var variableName = 'https://www.example.com/example.png';

    If there is security issues calling a http method then you will need a base64 version of the image held in the database. The base64 data would be populated from your database and set to a variable in JavaScript.

    var variableName = 'data:image/png;base64,iVBORw0KGgoAAUhEUgAABLAAAAXcCAYAAdaAAAAAAuI....';