简体   繁体   中英

Why is my JavaScript not working correctly in strict mode on Safari?

I have built a website that uses some simple JavaScript. After some testing, I have found that my JavaScript is behaving very differently on iOS devices as compared to all other devices that I could test with.

After several hours of trial-and-error, I have discovered that the unexpected behaviour occurs only in strict mode, but it has been very hard to troubleshoot the problem further because I am limited in my software/hardware for Apple development and testing.

Why could my code not be working in strict mode, and only certain (Apple, in particular) devices?

The possible problem

Your problem may be that you have made a const declaration with strict mode enabled.


A possible solution

If that is the case, and you would like to continue using strict mode, one solution is to use var instead of const , and simply be more careful to treat the variable as a constant.


More on this problem

It is in fact difficult to debug this problem without an OS X computer, because you are unable to use iOS Safari's remote console "Web Inspector".

However, according to caniuse , for the current versions of both Safari and iOS Safari (9.1 and 9.3, respectively, as of writing) const is:

Only recognized when NOT in strict mode

You can test this for yourself using the following example ( or this JSFiddle ). This code worked as expected for me with Chrome and Firefox on both Ubuntu and Android, but not on Firefox for iOS or iOS Safari.

HTML


<pre></pre>
<form>
    <input type="submit">
</form>

JS


"use strict";

var form = document.querySelector("form");
var info = document.querySelector("pre");

// This const declaration in conjunction with strict mode will
// cause this script not to work on iOS devices
const _MEANINGLESS = 0;

form.addEventListener("submit", function(event) {
    event.preventDefault();
    info.textContent = "Submit event captured.\n";
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM