cubiq / add-to-homescreen

Add to home screen call-out for mobile devices
http://cubiq.org/add-to-home-screen
2.29k stars 748 forks source link

With version 3.2.3, this.container is not defined #247

Open benlk opened 7 years ago

benlk commented 7 years ago

in ath.Class.prototype, in the function show:

        // attach all elements to the DOM
        this.viewport.appendChild(this.element);
        this.container.appendChild(this.viewport);

this.container is undefined, causing the following error:

addtohomescreen.js?ver=3.2.3:553 Uncaught TypeError: Cannot read property 'appendChild' of null

this.container appears to be defined in the function ath.Class:

// the element the message will be appended to
this.container = document.body;

But the this is not the same, and so this.container is not shared in the context of show()

benlk commented 7 years ago

This bug is not appearing in 3.2.2's unminified version, if that helps.

gwhenne commented 7 years ago

Using the unminified version gets rid of the error, but AddToHomescreen never appears. Localstorage is being updated with

org.cubiq.addtohome {"lastDisplayTime":1480609920899,"returningVisitor":true,"displayCount":1,"optedout":false,"added":false}
amboy00 commented 7 years ago

Try using window.onload when calling the script. I suspect you're getting the error because document.body is still null when the script is called.

This is what worked for me.

window.onload = function() {
  addToHomescreen();
}
benlk commented 7 years ago

If that's the case, then the docs at http://cubiq.org/add-to-home-screen should be updated to put the addToHomescreen(); call in the footer.

joshgrift commented 7 years ago

Had the same issue. Placing <script> addToHomescreen();</script> right after the <body> tag seemed to work.