I've got a server that loads an html page by echoing the result of a function *file_get_contents* to an URL. I want to get the URL that is clicked by the user after this. I've tried:
$result = file_get_contents('http://www.google.com/');
header('Content-Type: text/html; charset=iso-8859-1');
echo $result;
echo '<script type="text/javascript">',
"Event.observe(document.body, 'click', function(event) {",
'alert("hi");',
'});</script>';
But I don't know why it doesn't work!
Thank you
You want a script that looks like this:
(function() {
function onclick(event) {
event = event || window.event;
var target = event.target || event.srcElement;
if (target.tagName && target.tagName.toLowerCase() === 'a') {
alert(target.href);
}
}
if (document.body.addEventListener) {
document.body.addEventListener('click', onclick, false);
} else if (document.body.attachEvent) {
document.body.attachEvent('onclick', onclick);
}
})();
This will work in IE and other browsers without using any JS libraries.
a suggestion, using event delegation:
(function()
{
function callback(e)//IE doesn't pass event object, but we'll fix that
{
var target;
e = e || window.event;//get IE event
target = e.target || e.srcElement;//IE again
if (target.tagName !== 'A')
{
return true;
}
//a link has been clicked, target holds a reference to that link, e is the click event
alert(target.href);
//to prevent the link to be followed:
if (e.preventDefault)
{// all major browsers, except for ie
e.preventDefault();
e.stopPropagation();
return false;
}//now IE again:
e.returnValue = false;
e.cancelBubble = true;
return false;//not required to return here
}
if (document.body.addEventListener)
{
document.body.addEventListener('click',callback,false);
}
else
{
document.body.attachEvent('onclick',callback);//for IE > 9
}
})();
This way, you only bind 1 event listener, to 1 handler, and it deals with all links that are clicked anywhere on your page. If you only want to block/handle certain links, you could give them a distinct class, and edit the callback function like so:
if(target.tagName !== 'A')
//add extra check:
if (target.tagName !== 'A' && target.className !== 'handleThisLinkClass')
google JavaScript event delegation, it's a really useful feature, especially when dealing with a large collection of elements that need event handlers
Even simpler to understand, but this method uses JQuery, which is often included in many frameworks or cmses.
$(function(){
$('a').click(function(){
alert(this.href);
});
});
You should unbind a click events so that your events will start to work.
<?php
$result = file_get_contents('http://www.google.com/');
header('Content-Type: text/html; charset=iso-8859-1');
echo $result;
echo '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>';
echo '
<script type="text/javascript">
$(document).ready(function(){
$(document).unbind("click").click(function(){ alert("Hi!"); });
// similarly
$("a").unbind("click").click(function(){ alert($(this).attr("href")); return false; });
});
</script>';
?>
Related
I have tried many methods to detect browser close event through jQuery or JavaScript. But, unfortunately, I have not been able to detect the close. The onbeforeunload and onunload methods are also not working.
How do I detect the window close, unload, or beforeunload events?
Have you tried this code?
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
$(function () {
$("a").not('#lnkLogOut').click(function () {
window.onbeforeunload = null;
});
$(".btn").click(function () {
window.onbeforeunload = null;
});
});
The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements.
One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread.
Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.
The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the close button ('X').
$(window).on('mouseover', (function () {
window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
return "";
}
var prevKey="";
$(document).keydown(function (e) {
if (e.key=="F5") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
window.onbeforeunload = ConfirmLeave;
}
prevKey = e.key.toUpperCase();
});
The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().
Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.
$(document).ready(function()
{
$(window).bind("beforeunload", function() {
return confirm("Do you really want to close?");
});
});
For simple follow following steps:
open http://jsfiddle.net/
enter something into html, css or javascript box
try to close tab in chrome
It should show following picture:
Hi i got a tricky solution, which works only on new browsers:
just open a websocket to your server, when the user closes the window, the onclose event will be fired
Following script will give message on Chrome and IE:
<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here
return "Please click 'Stay on this Page' and we will give you candy";
};
</script>
Chrome
IE
on Firefox you will get generic message
Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.
Response to question in comment
F5 will fire event again, so will Atl+F4.
As Phoenix said, use jQuery .bind method, but for more browser compatibility you should return a String,
$(document).ready(function()
{
$(window).bind("beforeunload", function() {
return "Do you really want to close?";
});
});
more details can be found at : developer.mozilla.org
jQuery .bind() has been deprecated. Use .on() instead
$(window).on("beforeunload", function() {
runBeforeClose();
});
Maybe it's better to use the path detecting mouse.
In BrowserClosureNotice you have a demo example and pure javascript library to do it.
It isn't perfect, but avoid problems of document or mouse events...
<script type="text/javascript">
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "Are you sure you want to leave this page without placing the order ?";
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
});
</script>
Please try this code, this is working fine for me. This custom message is coming into Chrome browser but in Mozilla this message is not showing.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var validNavigation = false;
function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
var ref="load";
$.ajax({
type: 'get',
async: false,
url: 'logout.php',
data:
{
ref:ref
},
success:function(data)
{
console.log(data);
}
});
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
This is used for when logged in user close the browser or browser tab it will automatically logout the user account...
You can try something like this.
<html>
<head>
<title>test</title>
<script>
function openChecking(){
// alert("open");
var width = Number(screen.width-(screen.width*0.25));
var height = Number(screen.height-(screen.height*0.25));
var leftscr = Number((screen.width/2)-(width/2)); // center the window
var topscr = Number((screen.height/2)-(height/2));
var url = "";
var title = 'popup';
var properties = 'width='+width+', height='+height+', top='+topscr+', left='+leftscr;
var popup = window.open(url, title, properties);
var crono = window.setInterval(function() {
if (popup.closed !== false) { // !== opera compatibility reasons
window.clearInterval(crono);
checkClosed();
}
}, 250); //we check if the window is closed every 1/4 second
}
function checkClosed(){
alert("closed!!");
// do something
}
</script>
</head>
<body>
<button onclick="openChecking()">Click Me</button>
</body>
</html>
When the user closes the window, the callback will be fired.
l am using this code
var exitPop = false;
var nonFire = false;
window.onbeforeunload = function () {
if(!exitPop){
exitPop=true;
return 'Wait! YOU ARE TODAYS WINNER!';
}
};
setInterval(function(){
if(exitPop && !nonFire){
nonFire = true;
window.location.href = 'http://google.com';
}
}, 200);
but its also execute on clicking any html redirect button on page.. i want it execute only if someone close browser and it should support all browsers.
i need to add this at only one link in my site how can id do? i mean i am using this code for redirect
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.Event.subscribe('comment.create',
function (response) {
window.location = "http://domain.com";
});
FB.Event.subscribe('comments.remove',
function (response) {
window.location = "http://domain.com";
});
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
//]]>
</script>
so i want exit function do not execute for this.. so how do integrate this
I haven't tested it but you should be able to attach a 'click' event to every link on the page, which should set a global variable such as
linkClicked = true;
You can then check that variable in the unload event
if (!linkClicked) // variable is false so they must not have clicked on a link
{
// Some annoying message here
}
Disclaimer: this is pretty much pseudo code, it's not a copy+paste solution.
window.onbeforeunload does not distinguish between links, back/forward buttons, exit buttons or anything else. If fires when you leave the page, regardless of how you leave the page.
I have a div:
<div id="test" style="width:auto; height:auto;">
</div>
And a function:
$(function() {
$("#test").attr("contentEditable", "true");
$("#test")
.attr("tabindex", "0")
.keydown(function(){ alert(1); return false; })
.mousemove(function(){ alert(2); return false; });
});
How can I implement this code in JavaScript without including the JQuery library?
You can do it like this in javascript without using jquery, Demo available here JsFiddle
You can put it in onload method of body then it will call onload of body or just put it in script section below all controls without putting it in function then it will call when document is ready like jquery method $().ready();
var test = document.getElementById('test');
test.setAttribute("contentEditable", "true");
test.setAttribute("tabindex", "0");
test.onkeydown = function(event) { alert("KeyDown");}
test.onmousemove = function(event) { alert("MouseMove");}
function runme() {
var elm = document.getElementById("test");
elm.contentEditable = "true";
elm.tabIndex = 0;
elm.onkeydown = function() { alert(1); return false; };
elm.onmousemove = function() { alert(2); return false; };
}
if(window.addEventListener)
window.addEventListener("load", runme, false);
else
window.attachEvent("onload", runme);
Adil has the right idea, but to improve upon it a bit, you could store the element in a variable so you do not have to make a call to get the element every time. So I would change it to look something like this:
var t = document.getElementById('test');
t.setAttribute("contentEditable", "true");
t.setAttribute("tabindex", "0");
t.onkeydown = function(event) { alert("KeyDown");}
t.onmousemove = function(event) { alert("MouseMove");}
Upvoted Adil for beating me to it and for providing the jsfiddle link :)
updated: nevermind, since you just updated your post
I have a page within wordpress that I want to password protect via a user role plugin. Everything works fine on straight forward pages but I have a page with window.onload = function() { that completely overrides the password function.
I want the page to load immediately after it's checked to see if the user is logged in or not.
Update:
I'm using this plugin and I just have the function:
<script type="text/javascript">
(function() {
window.onload = function() {
var map = new google.maps.Map(document.getElementById('map'), options);
...
} } )
</script>
Which then loads on this div:
<div id="map" style="width:100%; height:100%"></div>
You have to use addEventListener or attachEvent to load multiple functions. If you want to use window.onload = .., use the code in the last else block at the function below:
function addEvent(name, func) {
if (window.addEventListener) {
window.addEventListener(name, func, true);
} else if(window.attachEvent) {
window.attachEvent('on' + name, func);
} else {
var other_func = typeof window['on'+name] == "function" ? window['on'+name] : function(){};
window['on' + name] = function(ev){
func(ev);
other_func(ev);
}
}
}
addEvent('load', function(){
//Load function
});
Instead of assigning it directly to the onload property add it as an event listener
https://developer.mozilla.org/en/DOM/element.addEventListener
You'll need to use attachEvent for IE versions < 9.
http://msdn.microsoft.com/en-us/library/ms536343(v=vs.85).aspx
If you're using a framework such as jQuery or Prototype this can be abstracted out so you don't need to worry about different browsers.
I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});