allowfullscreen
an HTML attribute for the iframe tag

What methods can I use to exit fullscreen mode programmatically?

Answers:

  • Exiting fullscreen mode programmatically can vary depending on the platform, environment, or framework you are using. Below are some methods for different scenarios:

    1. HTML5 / JavaScript in Web Browsers

    In a web environment, you can use the Fullscreen API to exit fullscreen mode.

    function exitFullscreen() {
        if (document.fullscreenElement) {
            document.exitFullscreen().catch(err => {
                console.error(`Error attempting to exit fullscreen: ${err.message}`);
            });
        }
    }
    

    To invoke this function, you might call it based on a user action, like clicking a button.

    2. React Applications

    In React, you can use the same Fullscreen API, integrating it within your component.

    import React from 'react';
    
    const YourComponent = () => {
        const exitFullscreen = () => {
            if (document.fullscreenElement) {
                document.exitFullscreen();
            }
        };
    
        return (
            <button onClick={exitFullscreen}>Exit Fullscreen</button>
        );
    };
    

    3. Electron Applications

    If you are using Electron, you can close the fullscreen from the BrowserWindow instance.

    const { BrowserWindow } = require('electron');
    
    // Assuming you have your window instance
    let win = new BrowserWindow({ /* options */ });
    
    // To exit fullscreen
    if (win.isFullScreen()) {
        win.setFullScreen(false);
    }
    

    4. Unity (C#)

    In Unity, you can toggle fullscreen mode and exit it:

    void ExitFullscreen() {
        Screen.fullScreen = false;
    }
    

    You can invoke this method based on user interaction, like a button press.

    5. JavaFX Applications

    In JavaFX, you can exit from fullscreen by manipulating the primary stage:

    if (primaryStage.isFullScreen()) {
        primaryStage.setFullScreen(false);
    }
    

    6. Other Frameworks

    If you’re using a specific framework or library (like React Native, Flutter, etc.), please refer to their documentation as the methods and API calls can vary.

    Summary

    Always ensure that the exit fullscreen action is taken based on user input due to browser policies that usually restrict such actions to user-initiated events.

Related Questions: