Viewport meta tag removes error

My webpage has absolutely no "meta" view tag.

I created my own "meta" view tag dynamically:

var viewportMeta = document.createElement('meta'); viewportMeta.setAttribute('id', 'myMeta'); viewportMeta.setAttribute('name', 'viewport'); viewportMeta.setAttribute('content', 'width=device-width, initial-scale=1.0, user-scalable=no'); 

and added it to "head" (after some user actions):

 document.head.appendChild(viewportMeta); 

Then (after the user clicks on some button) I need to remove the tag "myMeta" "meta" from "head":

 var myMeta = document.getElementById('myMeta'); document.head.removeChild(myMeta); 

And he removes, 100%! Tested with a desktop browser and Adobe Edge Inspect Weinre on iPad.

But the whole page does not go back to the previous state! The whole page remains unchanged, for example, it has a β€œmeta” viewport tag with all the defined properties in the viewportMeta object.

So, is there a way to completely remove the "meta" viewport tag? Any ideas?

(This issue affects the iPad Safari and Chrome browsers. I tried not to remove the "meta" tag, but just changed its "content" property - it failed. I did not check it on Android devices and browsers.)

+4
source share
1 answer

You must restore the viewport meta tag to its original value.

 <html> <head> <title>test dynamic view port</title> </head> <body> <button id="turnOn">on</button> <button id="turnOff">off</button> <script type="text/javascript"> function turnOnDeviceViewport() { removeMetaIfExist(); var viewportMeta = document.createElement('meta'); viewportMeta.setAttribute('id', 'myMeta'); viewportMeta.setAttribute('name', 'viewport'); viewportMeta.setAttribute('content', 'width=device-width, initial-scale=1.0, user-scalable=no'); document.head.appendChild(viewportMeta); alert("click"); } function turnOffDeviceViewport() { removeMetaIfExist(); var viewportMeta = document.createElement('meta'); viewportMeta.setAttribute('id', 'myMeta'); viewportMeta.setAttribute('name', 'viewport'); viewportMeta.setAttribute('content', 'width=980, user-scalable=yes'); document.head.appendChild(viewportMeta); alert("click"); } function removeMetaIfExist() { var metaElement = document.getElementById("myMeta"); if (metaElement) document.head.removeChild(metaElement); alert("removed"); } document.getElementById("turnOn").addEventListener("click", turnOnDeviceViewport, false); document.getElementById("turnOff").addEventListener("click", turnOffDeviceViewport, false); </script> </body> 

Details on metadata values ​​in viewport on Apple Developer website: Safari HTML reference: Supported meta tags

EDIT: the default viewport value "width = 980, user-scaleable = yes" may not be the same for all devices and browsers, so for a complete solution you will need to determine the browser that you are running and set the default value accordingly

+4
source

Source: https://habr.com/ru/post/1483338/


All Articles