Verify the compatibility of the device with ScreenOrientation.lock() function - An error occurred indicating that screen.orientation.lock() is not supported on this particular device

I've been trying to implement ScreenOrientation.lock() according to the documentation, but I'm having trouble getting it to work correctly.

https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/lock

When I use

window.screen.orientation.lock("portrait");
on Chrome desktop, I receive an error stating that
screen.orientation.lock() is not available on this device.
. Is there a way to determine if a device supports screen orientation locking?

I have already included "orientation":"portrait" in my manifest.json, but this only sets the default orientation and does not lock it.

https://www.w3.org/TR/appmanifest/#orientation-member

On a side note:

I had some difficulty understanding how to properly call the method. If anyone else encounters these errors:

ScreenOrientation.prototype.lock("portrait");

window.ScreenOrientation.prototype.lock("portrait");

It results in the following exception:

Unhandled Rejection (TypeError): Failed to execute 'lock' on 'ScreenOrientation': Illegal invocation

(ScreenOrientation as any).lock("portrait");

This leads to the following exception:

TypeError: ScreenOrientation.lock is not a function

Answer №1

Utilizing the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="noreferrer">Promise</a> feature, calling <code>window.screen.orientation.lock()
will return a promise. This promise will trigger one of the functions provided to a chained then() method based on whether the promise is resolved (success) or rejected (failure).

To execute window.screen.orientation.lock(), you can do it in this manner:

window.screen.orientation
    .lock("portrait")
    .then(
        success => console.log(success),
        failure => console.log(failure)
    )

You may want to include more relevant content in the resolve and reject methods, but this setup will at least handle rejection and prevent an Unhandled Rejection error from occurring.

Answer №2

Handling rotation in mobile devices often requires an event listener to manage the error related to screen.orientation.lock. This particular piece of code has proven effective for me.

The class .main-app is applied to the body tag.

To incorporate a button into your HTML code, include the following:

    <div id="lock-landscape-btn" class="hidden">Lock</div>
    <div id="unlock-orientation" class="hidden">unLock</div>

In your JS file or code, make sure to add an EventListener like so:

    function rotateScreen () {

        document.querySelector('#lock-landscape-btn').addEventListener('click', function () {

            if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {

                if(document.querySelector(".main-app").requestFullscreen) {
                    document.querySelector(".main-app").requestFullscreen();
                }else if(document.querySelector(".main-app").webkitRequestFullScreen) {
                    document.querySelector(".main-app").webkitRequestFullScreen();
                }

                screen.orientation.lock("landscape-primary")
                    .then(function() {
                        console.log('landscape-primary');
                    })
                    .catch(function(error) {
                        console.log(error);
                    });
            }

        });

        document.querySelector("#unlock-orientation").addEventListener('click', function() {
            screen.orientation.unlock();
        });
    };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Overflow of Primary Text in Material UI List Item

I apologize if this question has already been asked, but I have searched and couldn't find the solution! I am facing an issue with a Material UI listview that has a fixed width within a sidebar. The titles of some options are not properly rendering a ...

Lowest value malfunctioning

I have encountered an issue with setting minimum values for 4 things. All 4 things are supposed to have the same minimum value as the first thing, but when moving the slider, everything goes back to normal and works fine. Where could the problem be origina ...

What is the process for executing a PATCH request from an HTML form in NodeJS?

I recently tried to perform a patch request on an HTML form from the frontend to MongoDB database through a NodeJS API. Below is the structure of my Nodejs API: app.route("/requests/:rollno") .get(function(req, res) { // get method to find a q ...

"The CSS problem is that the input tags should be aligned in the same row instead of the second row

If you could take a look at this jsfiddle example Currently, I am using bootstrap tags for my system. However, when I add more than 6 or 7 input tags, they spill over into a second row. I want them to all fit within the first row, similar to the image sho ...

Maintain the modifications in NPM software dependencies

Currently, I am developing a REACT web application and have integrated the react-datasheet library using NPM. To ensure compatibility with IE11, I made modifications to the JavaScript file installed via NPM. While these changes work perfectly on my local m ...

Striving to implement a dynamic dropdown menu using React's <select> element and rendering users from an array as selectable options

I am currently working on a project to develop an application that allows users to be added to a MongoDb database and have their names displayed in a dropdown menu. While creating the form, I encountered two issues - one related to the closing tag error a ...

Endless loops: How React JS components can render indefinitely

Every time I try to render a screen with the Bar component, it seems to get stuck in an infinite loop without even passing any data. I tested importing react-chartjs-2 and that worked fine, loading just once. However, the other bar chart keeps rendering co ...

Unspecified outcome of Ajax array as a choice in Select

I'm fairly new to working with AJAX / JSON and I'm having trouble figuring out how to parse an AJAX array response into a <select> dropdown. Despite going through several online tutorials and attempting different approaches to return the r ...

Concluding a row in PHP Bootstrap for various grid dimensions

My grid layout for displaying a list of users now includes the classes col-xs-4 col-sm-4 col-md-3 col-lg-2. In the past, I only used col-md-2 and relied on a $counter to manage the row layout: while ($row = $business_query->fetch_assoc()){ ...

Incorporate a backdrop to enhance a material icon

I'm working with the following Material Icon code but I want to enhance it by adding a white background for better contrast. Any suggestions on how to achieve this? <a id="lnk_quick_print" href="javascript:;" title="Quick P ...

Arrange the array according to the values within each sub-array

Attempting to organize the items within an object/array based on their "name" attribute, Found guidance on this topic at Sort array of objects and put together the following code sample: var alphabet = { a: 1, b: 2, c: 3, d: 4, e: 5, ...

What is the process of organizing information with http in Angular 2?

Currently, I am working through a heroes tutorial and have made progress with the code so far. You can view the code <a href="https://plnkr.co/edit/YHzyzm6ZXt4ESr76mNuB?preview" rel="nofollow noreferrer">here</a>. My next goal is to implement ...

How to center a paragraph using Bootstrap:

I need help aligning my paragraphs on the same horizontal line. Can you provide a solution? foreach ($articles as $article): ?> <div class="container" id="presentation"> <div class="row"> <div class="col-12 mb-4"></div ...

Enhance the HTML content using a JavaScript function

Here is the code that I have: <label>Brand</label></br> <select name="brand" id="brand" onChange="changecat(this.value);"> <option value="" selected>Select Brand</option> <option value="A">AMD</option&g ...

Transforming the elements within an array of objects into individual key-value pairs and then adding them to a fresh array

Hello, I am diving into the world of Typescript/Javascript and encountering some challenges when it comes to manipulating arrays of data. Please bear with me as I navigate through my learning curve. Imagine having an array of objects structured like this: ...

Displaying a message within a picture

Is there a way to display the unread message count as text on my PNG image? You can find the image at header: span Messages =image_tag "login_icon6.png", class: 'img4' Unread count code: = current_user.mailbox.inbox(:unread =& ...

Attempting to iterate over the array of objects in order to discover a match

I am currently working with an object structure that resembles the one shown in the image linked below. My goal is to compare the inner object properties (such as massing type id) with existing IDs. If there is a match, I want to retrieve the name of that ...

Unable to persist data in MongoDB (Image of PopUp)

I encountered a problem where out of the 4 img options in the code below, only one image is not being saved to MongoDB (img2 from the popup). The other three images are being saved successfully. <div className="mt-10 grid grid-cols-1 gap-x-6 gap- ...

Utilizing Firebase's orderByChild feature to retrieve the latest posts

Is there a way to sort my query by the 'order_date' value and have it display in chronological order (latest orders first)? I'm also working on implementing pagination. Here is the code snippet for my current query. var orders = fbdatabase. ...

I am having trouble with my React Router v6 code - when I use the navigate function, the component does not load

As a beginner, I appreciate your patience as I navigate through this Codesandbox to learn about the newest version of React Router v6 Preview. Currently, I am encountering difficulties configuring the routes. My goal is simple - I have a button that, when ...