Block back button in a browser like whatsapp web - javascript

I develop a single page web application, i want to block back button to prevent the music stops when an user click to it! can anyone help me please!

Ok, there is complete, commented and tested example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script>
// Add actual page to history
history.pushState(null, null, location.pathname)
// Register back button click
window.onpopstate = function (e) {
// Prevent default action on back button click
e.preventDefault()
// Add actual page to history again
history.pushState(null, null, location.pathname)
}
</script>
</head>
<body>
</body>
</html>

Related

prevent user from clicking browser's back button

I want to disable the browser's back button. I have tried some javascript codes to implement the same. But those codes didn't meet my requirements. It works in firefox but not working in chrome and edge. Sometimes it works all the three but randomly working and not working.
Can anybody share me the script disable the back button in all browsers without flaws like random behaviour.
Here I showed some scripts I have tried
history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () => history.forward();
history.pushState(null, null, location.href);
history.back();
history.forward();
window.onpopstate = function () { history.go(1); };
You can refer to the following code. I test the code sample in Edge, Chrome and Firefox, it works well.
Save this file as a.html for the first page:
<!DOCTYPE html>
<html>
<head>
<title>First Page</title>
<script type="text/javascript">
function preventBack() {
window.history.forward();
}
setTimeout("preventBack()", 0);
window.onunload = function () { null };
</script>
</head>
<body>
<h3>This is first page</h3>
Goto second Page
</body>
</html>
Save this file as b.html for the second page:
<!DOCTYPE html>
<html>
<head>
<title>
Blocking Back Button using javascript
</title>
</head>
<body>
<h3>This is second page</h3>
<p>
On this page, back button functionality is disabled.
</p>
</body>
</html>
Run a.html and click to navigate to b.html. Then click browser's back button on b.html, it won't navigate to a.html.

Use 'window.open' and communicate with a child window

There are two pages in my tomcat server.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="onBtnClick()">jump to child</button>
<script>
const msg = {
name:'index.html',
ifor:'I am your parent!'
};
function onBtnClick() {
const childWindow = window.open('./child.html');
childWindow.msg = msg
}
</script>
</body>
</html>
child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="msg-panel"></div>
<script>
const msgPanel = document.querySelector('#msg-panel');
msgPanel.innerHTML = `<span>${msg.name}</span><br><span>${msg.ifor}</span>`
console.log(window.msg);
</script>
</body>
</html>
I want to pass some message( the msg Object in index.html) from index.html to child.html, by the way above.
When I click the button in index.html to open the child.html, sometimes I can get the msg object in child.html, but sometimes I can't.
make the button type="button"
you set the message after opening. Sometimes the computer will be faster and not pass the message before it is shown. Use a timeout to show the message in the child OR
store the message in sessionStorage before calling window.open OR
have the child read the message from the parent:
const msgPanel = document.querySelector('#msg-panel');
msgPanel.innerHTML = `<span>${opener.msg.name}</span><br><span>${opener.msg.ifor}</span>`
console.log(window.msg);
Because you sometimes get that message and sometimes not try to put code from script from index.html in this:
document.addEventListener("DOMContentLoaded", function(event) {
//your code...
}
I think your html is not loaded and you click the button too fast.
Although this is already solved. Another alternative for sending data to a child would be localstorage. Getting and setting is really easy and IE11 is also supported.
localStorage.setItem('msg', 'something important');
let msg = localStorage.getItem('msg');
With that you would also have the ability to send data back and forth by setting event listeners on the localstorage change event like
window.addEventListener('storage', function(e) {
//do some cool stuff here
}
Just in case you want to have a more complex exchange between parent and child.

auto click a link when page loads doesn't work

I have a page for redirect purpose, I want to redirect user to another page once it hits this page:
<!DOCTYPE html>
<html>
<head>
<title>Open App</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert("test"); //this shows up.
$('#openApp').click(); //this button is not clicked.
});
</script>
</head>
<body>
redirect
</body>
</html>
I want the redirect happen once this page is load. But the click function is not fired. I have to click the link by myself to redirect to google.com.
I normally wouldn't give you an alternative as an answer, but looking at your comments, it looks like you're just trying to redirect.
You can use window.location.replace('http://www.google.com'); for that.
$(document).ready(function () {
window.location.replace('http://www.google.com');
});
See also, this answer.
It's not possible to trigger a click event without any user interaction. In other words, if the function being called wasn't called from a user interaction, the click event will not get triggered.
In your case, simply update the window.location attribute:
window.location = 'http://www.google.com';
try this fiddle mate, added script is
$(document).ready(function () {
//this shows up.
$('#openApp')[0].click(); //this button is not clicked.
});

Unexpected click behaviour on link + popup click in Google iOS app

I'm having following problem. I have following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Click Me test site</title>
</head>
<body>
Click Me
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(document).ready(function() {
var handler = function codeclick(event) {
var link_new = $('a').attr('co-target');
if (link_new) {
window.open(link_new, '_blank');
}
}
$('a').bind('click.codeclick', handler);
});
</script>
</body>
</html>
You can see it in action here
The expected behaviour on desktop is that the page in co-target attribute is opened in new tab/window and the one in href attribute is opened in current tab.
On internal mobile facebook browser it should open just the co-target attribute page (intended). But on Google mobile iOS app it opens the page in href attribute (unintended).
Does anyone encountered similar problem before and maybe have some clues what should I do to make it right? There is no need that the page in co-target has to open. I just want it that on both facebook and google app it open one of it, not different one in each.

Page redirecting before asynchronous Javascript loads

I'm trying to make a redirect page that tracks the loading of that page with mixpanel.track
The problem is, the page redirects before the async javascript has time to download and run. What do I do?
Here is my code.
Edit: I'm putting the code in the question.
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<!-- start Mixpanel --><script type="text/javascript">(function(f,b){if(!b.__SV){var a,e,i,g;window.mixpanel=b;b._i=[];b.init=function(a,e,d){function f(b,h){var a=h.split(".");2==a.length&&(b=b[a[0]],h=a[1]);b[h]=function(){b.push([h].concat(Array.prototype.slice.call(arguments,0)))}}var c=b;"undefined"!==typeof d?c=b[d]=[]:d="mixpanel";c.people=c.people||[];c.toString=function(b){var a="mixpanel";"mixpanel"!==d&&(a+="."+d);b||(a+=" (stub)");return a};c.people.toString=function(){return c.toString(1)+".people (stub)"};i="disable track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config people.set people.set_once people.increment people.append people.track_charge people.clear_charges people.delete_user".split(" ");
for(g=0;g<i.length;g++)f(c,i[g]);b._i.push([a,e,d])};b.__SV=1.2;a=f.createElement("script");a.type="text/javascript";a.async=!0;a.src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js";e=f.getElementsByTagName("script")[0];e.parentNode.insertBefore(a,e)}})(document,window.mixpanel||[]);
mixpanel.init("9f85e6edf009562d5ac2c944b0da6398");mixpanel.track("CBhopID_x3cw17x1h")</script><!-- end Mixpanel -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta content="1;url=http://e20f07o0yd5b2re0-x3cw17x1h.hop.clickbank.net/" http-equiv="refresh" />
<script type="text/javascript">
window.location.href = "http://e20f07o0yd5b2re0-x3cw17x1h.hop.clickbank.net/"
</script>
<title>Redirecting...</title>
</head>
<body>
<p>If you are not redirected automatically, follow this link.</p>
</body>
</html>
mixpanel.track() has callback option which will be called after tracking event, you need to use it, on callback you could redirect to some location, place your window.location code inside the callback function, like:
mixpanel.track("CBhopID_x3cw17x1h", {}, function() {
window.location.href = "http://e20f07o0yd5b2re0-x3cw17x1h.hop.clickbank.net/";
});

Categories