How to save fullscreen state in Firefox? - javascript

Following Mozilla's API document on Fullscreen, I've placed the following code in my website, it simply takes the whole document (html element) and makes the page go fullscreen once the user clicks anywhere in the page, and once there's another click, page goes back to normal.
var videoElement = document.getElementsByTagName('html')[0];
function toggleFullScreen() {
if (!document.mozFullScreen) {
if (videoElement.mozRequestFullScreen) {
videoElement.mozRequestFullScreen();
}
} else {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
}
}
}
window.addEventListener("click", function(e) {
toggleFullScreen();
}, false);
My question is how can I save this fullscreen state so every time that Firefox loads up, that page is still on fullscreen.
Or any workaround? This is for Firefox for Android.

It's an extreme workaround, but you can make your website a progressive web app and put "display": "fullscreen" in its manifest. Then you can launch your site from the home screen and use it like a fullscreen native app.

Following my experiments and the specs, this isn't doable, from client browser javascript
This api need an user interaction. We can't activate the fullscreen by scripting.
From the fullscreen api specification:
Fullscreen is supported if there is no previously-established user
preference, security risk, or platform limitation.
An algorithm is allowed to request fullscreen if one of the following
is true:
The algorithm is triggered by user activation.
The algorithm is triggered by a user generated orientation change.
https://fullscreen.spec.whatwg.org/#model
About activation events:
An algorithm is triggered by user activation if any of the following
conditions is true:
The task in which the algorithm is running is currently processing an
activation behavior whose click event's isTrusted attribute is true.
The task in which the algorithm is running is currently running the
event listener for an event whose isTrusted attribute is true and
whose type is one of:
change
click
dblclick
mouseup
pointerup
reset
submit
touchend
https://html.spec.whatwg.org/multipage/interaction.html#triggered-by-user-activation
We can't trigger fullscreens from scripts, or if so, the script must be triggered by the user.
Including simulating a click won't works, this is regular behavior, made to protect user experience.
With some reflexion, we can't agree more on this, imagine any ads page can launch full screens, the web would be a hell to browse!
You told in comment: «I am the only user here»
What you can do if using unix: (( probably alternatives exists in other os )).
Using midori (a lightweight webkit browser), this will start a real fullscreen.
midori -e Fullscreen -a myurl.html
There is no ways to start firefox or chromium in a fullscreen state from the command line, to my knowledge.
But what is doable is to trigger a F11 click at system level, focusing on the good window, just after the page launch. ((sendkey in android adb shell?))
xdotool can do that.
Here is a pipe command line that will launch firefox with myurl.html, search for the most recent firefox window id, then trigger the F11 key on this window.. (Press F11 again to exit)
firefox myurl.html && xdotool search --name firefox | tail -1 | xdotool key F11
This should be easy to adapt for other browsers.
As last alternative, have a look at electron or nw.js.

take a look at this add on for Firefox, i have not tried it, as I'm posting this from mobile, it's description does say that it can force start in full screen. I'm just quoting their description .
Saves the last state or force start in full screen forever! Simple and
complete for this purpose.
Edit : And the link to it
https://addons.mozilla.org/en-US/firefox/addon/mfull/

What about using localStorage like this?
function goFullScreen() {
if (videoElement.mozRequestFullScreen) {
localStorage.setItem('fullscreenEnabled', true)
videoElement.mozRequestFullScreen();
}
}
window.onload = function () {
if (localStorage.getItem('fullscreenEnabled') === true) {
goFullScreen();
}
};
function toggleFullScreen() {
if (!document.mozFullScreen) {
goFullScreen();
} else {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
localStorage.setItem('fullscreenEnabled', false)
}
}
}
window.addEventListener("click", function(e) {
toggleFullScreen();
}, false)

Related

Browser denying javascript play()

I have a page with an input field for scanning products. When a barcode is scanned or a SKU is typed into the field, an ajax request is made and the application plays either a success or an error sound depending on the response using HTMLMediaElement.play().
sounds.error.play();
This was working fine a while ago but now I get this error:
⚠ Autoplay is only allowed when approved by the user, the site is activated by the user, or media is muted.
Followed by:
NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
Since this page only exists for the purpose of scanning SKUs, when the page loads, that input field is programmatically focused so as to make things easier on the end user. I tried removing this focus so that the user must click into the input field, but that doesn't appear to satisfy whatever the requirements are to allow playing of audio
After a bit more experimenting I found that with some additional amount of user interaction, the sound will play. For instance if I create a checkbox to "enable" the sound and the user clicks it, that appears to be enough. Or if the user clicks outside of the input element and then back into to it again that also works.
What exactly are the requirements that will satisfy most modern browsers so that they will allow playing of audio?
I realize the answer may be different for different browsers and configurations, but I was unable to find anything authoritative for current versions of either Firefox or Chrome. I'm looking for a workaround so that the application does not need to be complicated with extra clicks or other kinds of interactions, and since I am now aware of this new policy, I'd like the revisions to be as unobtrusive as possible.
UPDATE:
Here is a basic example I worked up to demonstrate the issue. I tried three different browsers just now and they all behaved a bit differently. Firefox in particular behaves as described above — does not play the sound until I focus on the input field, blur, then click to focus again:
http://so.dev.zuma-design.com/input-sounds.html
There is some permission blocking in all modern browser (especially chrome) when comes down to autoplaying multimedia.
Here is the Autoplay availability's section from MDN which shows when the media will be allowed to execute automatically:
The audio is muted or its volume is set to 0;
The user has interacted with the site (by clicking, tapping,
pressing keys, etc.)
If the site has been whitelisted; this may happen
either automatically if the browser determines that the user engages
with media frequently, or manually through preferences or other user
interface features
If the autoplay feature policy is used to grant
autoplay support to an <iframe> and its document.
This here is a similar solution for what you want with arrayBuffer using AJAX
here is a DEMO
I struggled with that same issue as well and out of the blue I fixed that very easily:
Just change your event listener at your play button
onClick={togglePlay} to
onClickCapture={togglePlay}
Example in React using hooks:
const Player = ({ audio }) => {
const [playing, setPlaying] = useState(false);
const togglePlaying = () => setPlaying((prev) => !prev);
useEffect(() => {
if (audioRef && audioRef.current) {
if (playing) {
audioRef.current.play();
} else {
audioRef.current.pause();
}
}
}, [playing]);
return (
<audio
autoPlay=""
src={audio}
ref={audioRef}
onTimeUpdate={(e) => setCurrentTime(e.target.currentTime)}
onCanPlay={(e) => setDur(e.target.duration)}
onEnded={songEnded}
/>
<PlayerStart onClickCapture={togglePlaying}>
{playing ? <PauseIcon /> : <PlayIcon />}
</PlayerStart>
)
}
In safari to allowing autoplay in video tags you need add to them playsinline attribute. Like this:
<video autoplay="" muted="" playsinline=""></video>
[edit] Firefox 70 fixes this issue. The rest of this answer provides an explanation and the proposed workaround.
As you wondered about what specifically "The user has interacted with the site" criteria means:
Note that there's currently no requirement for the autoplay to be triggered in response to a user gesture (though Mozilla considers changing this). The user must interact with the page to "activate" it, after which autoplay is allowed.
According to a comment in Firefox source code,
["activation" is triggered by] events which are likely to be user interaction with the document, rather than the byproduct of interaction with the browser (i.e. a keypress to scroll the view port, keyboard shortcuts, etc).
Specifically, in the current development version of Firefox, the following events do NOT make the page "user-gesture-activated" (code):
Events targeted at a text input or an editable document (e.g. contenteditable), e.g. typing/clicking on a text input; - this was the exception that affected your use-case; now removed in Firefox 70.
Key presses that don't correspond to printable characters, enter or space; or any keys pressed while holding modifiers, such as CTRL)
Touch events that are not taps (e.g. swiping, panning, scrolling)
An idea - start with a fake/blurred textbox, and show/focus the real textbox after the first character is typed (adding the first character to the text input via JS) - the following code appears to work in Firefox:
$(document).one('keypress', function(ev) {
// copy the first character typed over to the text input
let char = String.fromCharCode(ev.which);
$('.play').val(char).focus();
});
$('.play').on('keypress', function() {
if($(this).val().length === 3) { // assuming you want to validate when a certain number of characters is typed
sounds[$(this).data('sound')].play();
}
})
This won't help if the user starts by clicking the text input, but a fallback non-audible feedback could be implemented for this case.

Website toggling full screen mode in Chrome, after ajax load

I still fighting with one Chrome issue on my webpage. There is pagination, that loads content via ajax call:
https://elody.cz/nase-nevesty
When I click 2nd, 3d, .. tab in pagination. The load is being performed and after that, it jumps into fullscreen mode.
You can also check on this video:
https://www.loom.com/share/768557e080f1471393aa0377d3fec024
I have this issue on Mac as well as on Windows – in Chrome.
Please, do anybody know how to fix that?
Thank you!
Filip
Inside ba_gallery.js there is following line:
var fullscreen = true;
set this value to false may solve your problem, i guess its worth a try
After ajax is done you could verify if its in fullscreen mode, if yes set its to false.
document.fullscreenEnabled : test id browser supports fullscreen
document.documentElement.requestFullscreen(); turn your page in to fullscreen
document.addEventListener("fullscreenchange", function (event) {
if (document.fullscreenElement) {
// fullscreen is activated
} else {
// fullscreen is cancelled
}
});
testing if its in full screen
document.exitFullscreen(); getting out

Confirmation before leaving/closing of tab?

I'm trying to show a confirmation pop before user close the tab or went to another tab like facebook, gmail, GoDaddy & others do.
My code working for Firefox but not for other browser like chrome, safari etc.
<script type="text/javascript">
var hook = true;
window.onbeforeunload = function() {
if (hook) {
return "Did you save"
}
}
function unhook() {
hook=false;
}
</script>
Call unhook() onClick for button and links
No Block URL
Please help me to get this fixed.
If you take a look at the api of window.beforeunload(), you can see that, though widely the basic unload event is supported, a custom message can only be set in internet explorer and certain versions of some browsers. So just use the normal standard message.
This feature (custom messages) was often exploited by malicous sites to interact with user in a harmful or malipulative way. This is why many browsers don't support this anymore, until some patch removes the threat for users.
Standard message solution:
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
});
Look at Ouibounce it helps detect when a user is about to leave the page(It looks at the position of the cursor). You could probably build off this library.

How to check if an application is minimized in javascript? [duplicate]

Hi i have notification div(divNotify) with some information and a timer in masterpage
Protected Sub Timer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
Me.GetNotification_Stats()
ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "Alert", "Show_NotifyDiv();", True)
Catch ex As Exception
Me.lblError.Visible = True
Me.lblError.InnerText = ex.Message
End Try
End Sub
divNotify will display in some interval of time.
here i need when the user will minimize the browser he will be notified by blinking browser and change color of browser
but first of all how do i know if the browser is minimized or not in javasript
here i am using jquery for show div tag
function Show_NotifyDiv() {
$("#div_NotificationOuter").show(1000);
$("#div_NotificationOuter").animate({ bottom: '+=30px' }, 4000);
}
Its impossible to find out whether the page is minimized via JavaScript, but you can use Visibility API to determine, whether the page is visible to user or not.
Currently available in Chrome, Mozilla and IE10.
https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API
http://code.google.com/chrome/whitepapers/pagevisibility.html
http://www.nczonline.net/blog/2011/08/09/introduction-to-the-page-visibility-api/
The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page.
Notes: The Page Visibility API is especially useful for saving
resources and improving performance by letting a page avoid performing
unnecessary tasks when the document isn't visible.
When the user minimizes the window or switches to another tab, the API sends a visibilitychange event to let listeners know the state of the page has changed. You can detect the event and perform some actions or behave differently. For example, if your web app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user returns to the tab. The user doesn't lose their place in the video, the video's soundtrack doesn't interfere with audio in the new foreground tab, and the user doesn't miss any of the video in the meantime.
Use cases
Let's consider a few use cases for the Page Visibility API.
A site has an image carousel that shouldn't advance to the next slide unless the user is viewing the page
An application showing a dashboard of information doesn't want to poll the server for updates when the page isn't visible
A page wants to detect when it is being prerendered so it can keep accurate count of page views
A site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off)
Developers have historically used imperfect proxies to detect this. For example, watching for blur and focus events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user. The Page Visibility API addresses this.
Example
View live example (video with sound).
The example, which pauses the video when you switch to another tab and plays again when you return to its tab, was created with the following code:
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
var videoElement = document.getElementById("videoElement");
// If the page is hidden, pause the video;
// if the page is shown, play the video
function handleVisibilityChange() {
if (document[hidden]) {
videoElement.pause();
} else {
videoElement.play();
}
}
// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || hidden === undefined) {
console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
// Handle page visibility change
document.addEventListener(visibilityChange, handleVisibilityChange, false);
// When the video pauses, set the title.
// This shows the paused
videoElement.addEventListener("pause", function(){
document.title = 'Paused';
}, false);
// When the video plays, set the title.
videoElement.addEventListener("play", function(){
document.title = 'Playing';
}, false);
}
Source: MDN: Page Visibility API
Additionally to c69's Answer, I would propose the library isVisible.
It has utility functions to access the W3C Page visibility API and you do not have to worry about cross browser support (unifies moz- or webkit-prefixed functions)
maybe check the size of the window? i'm just guessing.
We will be patient, but visibilityState is coming:
W3C defines the visibility state

How to White-Out/Black-Out Screen on PrintScreenButton Click?

How would the PrintScreenButton be prevented?
Have seen a whited-out screen for the Windows PrintScreenButton, and, in another instance, a blacked-out screen as soon as the Apple Screen-Capture function is enabled..
This is for development purposes.. To protect pre-production graphics.. Pre-Alpha, for feedback..
While this is not a recommended practice, it should be possible to listen to the PrtScrn keypress and hide everything until it's released.
However, this can easily be circumvented by having another window active and pressing the key.
$(document).on('keydown',function(e){
if(e.keyCode == 44) { //print screen button
$('body').hide();
}
}).on('keyup',function() {
$('body').show();
});

Categories