'How to detect when Mapbox/Leaflet enters or exits fullscreen mode

How can I detect when Mapbox or Leaflet enters or exits fullscreen mode?

I found this answer where someone said this:

Documentation says:

map.on('fullscreenchange', function () {
    if (map.isFullscreen()) {
        console.log('entered fullscreen');
    } else {
        console.log('exited fullscreen');
    }
});

If doesnt work, use this instead:

map.on('enterFullscreen', function(){
});

map.on('exitFullscreen', function(){
});

I tried that, as well as a few variations of the event type parameter. No dice.

Also, the documentation doesn't mention an event for this.

Note that I am using Mapbox GL JS.



Solution 1:[1]

I know this is a late response but to anyone in the future this is how I approached it (for mapbox GL JS (without leaflet).

map.on("resize", () => {
    if (document.fullscreenElement) // do something
});

You can give the map wrapper div a name and exclusively also check if the map is what triggered the fullscreen event

map.on("resize", () => {
    if (document.fullscreenElement?.attributes.name.value === "mapWrapper") // do something
});

And if you are using React you can use a state to hold this information.

const [isFullScreen, setIsFullScreen] = useState();
...
map.on("resize", () => {
  setIsFullScreen(
    document.fullscreenElement?.attributes.name.value === "mapWrapper"
  );
});
...
if (isFullScreen) //do something

Solution 2:[2]

This is actually really simple. You don't need anything from Leaflet or Mapbox. Just use an event listener on the document object.

let fullScreenChange;  

if ('onfullscreenchange' in window.document) {
  fullScreenChange = 'fullscreenchange';
} else if ('onmozfullscreenchange' in window.document) {
  fullScreenChange = 'mozfullscreenchange';
} else if ('onwebkitfullscreenchange' in window.document) {
  fullScreenChange = 'webkitfullscreenchange';
} else if ('onmsfullscreenchange' in window.document) {
  fullScreenChange = 'MSFullscreenChange';
}

function onFullscreenChange() {
   // Your stuff.
}

window.document.addEventListener(fullScreenChange, onFullscreenChange);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rymanso
Solution 2 BBaysinger