Saving on localStorage from an HTML Imports file

610 Views Asked by At

I'm using HTML imports, as a vehicle to dynamically inject content on a website. It works, perfect, there is a good article which exposes the use of imports on both files and templates.

Indeed there are few other articles, but Bidelman's is the most extensive. It covers scripting in imports. However, being able to render the imported content and being able to run scripts, I cannot make it save data on the local storage.

I can run scripts from the imported file, in the importer file, like an alert. However is impossible to catch the data I need to store and store it. How can this be achieved? Here is a sample of my code.

I have a simple select whose id is dim_city. The script to capture value on change and store on localstorage is very simple:

 var ie = importDoc.querySelector('#dim_city');   // capture the selector value.
   function getData() {
   var idc=ie.options[ie.selectedIndex].value;
   var  dataCi=(idc);
   localStorage.setItem("ic", dataCi);
   var storedData = localStorage.getItem(dataCi);

   mainDoc.body.appendChild(dataCi.cloneNode(true)); // this adds tha captured data to importer file.
 }    

As a single file, it runs fine and stores data on the localStorage. When imported, it runs scripts, like alert, but cannot store on localStorage.

Obviously the browser is supporting HTML Imports.

2

There are 2 best solutions below

0
On

I've found the solution, yes, any imported file is saving data on the localStorage. So I'm going to answer myself:

The problem is getting values from the property options of the selector. This is an old method, and it appears to conflict in Chrome, when imported. So the solution is to instead of this to get the selected value:

var idc=ie.options[ie.selectedIndex].value;

use this:

var idc=docuemnt.getElementById('dim_city').value;

On the other hand, let me clarify that it's true that any imported file's DOM is not part of the importer DOM, it can access both it's own DOM and master - importer's DOM, referencing and appending it's DOM to master's.

0
On

According to the definition, an import doesn't have a browsing context, so there is no localStorage.

http://w3c.github.io/webcomponents/spec/imports/#terminology