Search code examples
visual-studio-2013windows-phone-8.1innerhtmlvisual-studio-cordovacordova-4

cordova windows phone 8.1 : innerHTML add extra html tags


I use Visual Studio 2013 (Community) to create an app with Cordova 4.3.0. I target WP8.1 ("Windows Phone (Universal)" setting for the emulator).

I created an application from the template "Blank App (Apache Cordova)" from VS2013.
Then, I added a simple code that modifying the DOM with document.innerHTML when the deviceready event is listened.

var elt = document.getElementById('test');
elt.innerHTML = '<p>add a P in the DIV</p>';

Before the update I have :

<div id="test"></div>

And after javascript do the job :

<div id="test">
  <head></head>
  <body>
    <p>add a P in the DIV</p>
  </body>
</div>

The <p> is wrapped in <body> as if <div> were <html>

If I use Windows Phone 8 (not 8.1) emulator (or device) this does not happen.

I need to dynamically inject DOM elements but it is impossible with this bug. Use the append() or prepend() merthods has the same bug.

How can I fix it ?


edit: If I use node manipulation the result is correct.

var para = document.createElement("p");
var node = document.createTextNode("add a P in the DIV");
para.appendChild(node);

var element = document.getElementById("test");
element.appendChild(para);

But creating an HTML structure more complex, it quickly becomes very verbose.

No idea ?


I've found another solution that is more pretty.

var elt = document.getElementById('test');
elt.innerHTML = '';  // remove content works without head/body insertion
elt.insertAdjacentHTML('beforeend', '<p>add a P in the DIV</p>');

Solution

  • innerHTML is blocked by security rules by default in at the platform level for Windows JavaScript Apps as it poses a risk for script injection. This platform is the basis for both the Windows and Windows Phone 8.1 support.

    Fortunately there is a ployfill designed to alleviate this pain point: https://github.com/MSOpenTech/winstore-jscompat

    There was a bug in the jscompat shim previously that can cause extra HTML elements to be added to the DOM. The jscompat shim is included in VS templates by default and only is active for the Windows platform (not WP8), so this may be what you are running into. Grab the latest library from the link above and it should resolve your issue.