How to handle javascript onorientationchange event inside uiwebview

Can anyone help me handle the javascript orientation change event when visiting via uiwebview on iphone?

I am trying to capture the onorientationchange javascript event. I tried the following code.

 <style type="text/css" media="only screen and (max-device-width: 480px)"> .portrait { width: 300px; padding: 0 15px 0 5px; } .landscape { width: 460px; padding: 0 15px 0 5px; } </style> <script type="text/javascript"> window.onload = orientationchange; window.onorientationchange = orientationchange; function orientationchange() { if (window.orientation == 90 || window.orientation == -90) { document.getElementById('contents').className = 'landscape'; } else { document.getElementById('contents').className = 'portrait'; } } </script> // and I have a div inside html <div id="contents"> my contents and description... etc, and etc.. </div> 

It works fine in safari, but when I visit the page using uiwebview, the orientation change event is not fixed, and my desired functionality cannot be achieved.

+4
source share
3 answers

I would like to point you to this post: "iphone-uiwebview-local-resources-using-javascript-and-handling-onorientationchang" , the answer right below the accepted answer pays tribute to your question: handle orientation changes in the application code and make changes using javascript. I quote in the hope that the author will not mind:

"The answer to your second onorientationchange handler problem that is not called in the UIWebView:

I noticed that the window.orientation property is not working properly, and the window.onorientationchange handler is not called. This problem causes most applications. This can be fixed by setting the window.orientation property and calling window.onorientationchange in the willRotateToInterfaceOrientation method of the view controller that contains your UIWebView: "

+4
source

Thanks.

Another way to write this:

 var onorientationchange = function() { document.getElementById('contents').className = Math.abs(window.orientation == 90)? "landscape" : "portrait"; } window.onload = function() { window.onorientationchange = window.onorientationchange } 
+1
source

Put this in viewDidLoad :

 [[UIDevice currentDevice]beginGeneratingDeviceOrientationNotifications]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hasOrientationChanged:) name:@"UIDeviceOrientationDidChangeNotification" object:nil]; - (void)hasOrientationChanged:(NSNotification *)notification { UIDeviceOrientation currentOrientation; currentOrientation = [[UIDevice currentDevice] orientation]; if(currentOrientation == UIDeviceOrientationLandscapeLeft){ NSLog(@"left"); } if(currentOrientation == UIDeviceOrientationLandscapeRight){ NSLog(@"right"); } } 

Now you can call your webview with the correct orientation :)

+1
source

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


All Articles