In the body element I have 'onBeforeUnload = "leaveChat()";' with the purpose of eliminating the user ID from the database when he leaves the page (function code below). The function does its job when the user refreshes the page and when he goes to another URL. The problem is when the user closes the tab/browser directly, because his userID isn't deleted from the databases.
What do I have to add/remove from my code, so my script can eliminate the userID everytime, even when the users are closing the browser?
function leaveChat()
{
playTitleFlag = false;
xmlHttp3 = GetXmlHttpObject();
if (xmlHttp3 == null)
{
alert("Browser does not support HTTP Request");
return;
}
var url = "leaveChat.php?userId=" + userId;
xmlHttp3.open("GET", url, true);
xmlHttp3.onreadystatechange = stateChanged3;
xmlHttp3.send(null);
}
function stateChanged3()
{
}
Related
I'm making a system that uses authorization through an external API (VK). When the user clicks on "authorize via VK", they get a popup window where they can choose whether to grant permissions or cancel. Whatever they choose, the API just redirects them to my php script in the same popup window, and when that script is done, they are ending up with an empty popup window still open.
I need to do 2 things:
1) Close the popup window after the script is done.
2) Depending on what the function in the script returns, display the appropriate message for the user, not in that popup window, but in the initial window that initiated the popup (somewhere between the lines of the already existing text), after the popup has already closed.
Now, I don't know how to do this. There must me some javascript (preferrably jquery) that inserts a message to the initial window depending on the response obtained from the function that was called in a popup window that has already closed.
Here are some excerpts from the system:
http://example.com/vkcode?error=access_denied&error_reason=user_denied&error_description=User+denied+your+request&state=secret_state_code - this is the page the user gets redirected to (inside the popup) if they choose "cancel". And they keep staying on the blank page with that string in their address bar.
Here is some PHP code that handles the response from VK API:
public function vkAuthHandler() {
if (isset($_GET['error'])) {
if ($_GET['error_reason'] == 'user_denied' {
return 'user_denied';
}
else return 'error';
}
else {
// ... haven't written other logic yet, it's irrelevant anyway
}
return new Response();
}
Now, if I receive 'user_denied' response, I need to display a message telling the user that they refused the permissions. But not in that popup window where that function was called (it should already be closed by the time), but on the initial page, without reloading it.
I solved it in a sophisticated way. Not going to accept this answer because maybe someone offers a simplier solution.
In PHP:
public function vkAuthHandler() {
if (isset($_GET['error'])) {
if ($_GET['error_reason'] == 'user_denied' {
header('Set-cookie: vkresp=user_denied');
}
else header('Set-cookie: vkresp=error');
}
else {
// ...
}
echo "<script>window.close();</script>"; //closing the window here
return new Response();
}
In JavaScript (used jQuery and JS-Cookie), based on this solution:
var cookieRegistry = [];
function listenCookieChange(cookieName, callback) {
setInterval(function() {
if (cookieRegistry[cookieName] || Cookies.get(cookieName) != null) {
if (Cookies.get(cookieName) != cookieRegistry[cookieName]) {
cookieRegistry[cookieName] = Cookies.get(cookieName);
return callback();
}
} else {
cookieRegistry[cookieName] = Cookies.get(cookieName);
}
}, 100);
}
listenCookieChange('vkresp', function() {
if (Cookies.get('vkresp') == 'user_denied') {
console.log('VK response is user_denied');
$("#VKauth").append('<div style="color: red;">You denied authorization! Comments are blocked!</div>');
}
else if (Cookies.get('vkresp') == 'error') {
console.log('VK response is user_denied');
$("#VKauth").append('<div style="color: red;">Unknown authorization error. Try again.</div>');
}
Cookies.remove('vkresp');
});
$("#VKauth") is basically selecting an HTML element with the id VKauth on my page.
I have a Javascript snippet which my clients put on their websites. In order to track clicks, I create an XMLHttpRequest, wait for the 200 status and then propagate the click.
Here's the relevant code for the click event:
function pingServer(done) {
var url = "http://www.example.com/api/events/?eventID=" + eventID;
var invocation = new XMLHttpRequest();
invocation.open('GET', url, true);
invocation.withCredentials = true;
invocation.onreadystatechange = function() {
if (invocation.readyState == invocation.LOADING && invocation.status == 200) {
(typeof done === 'function' && done());
}
};
invocation.send();
}
// get the href
var href = e.target.href;
// ping then redirect
pingServer(function () { window.location.href = href; });
It works perfectly, and I get the ping on my server. The problem is that the delay in waiting for the XMLHttpRequest 200 code is noticeable to the end user. The browser's spinner doesn't start spinning until after that wait. So to the user it's poor UX and it looks like the click didn't do anything.
Is there a more user friendly way of registering a click event while also immediately handling the link redirect?
I'm working with a Google-Extention which allows me to open a new tab containing a form. After the form gets filled out and saved, every time I open this tab again the form should be prefilled with the data saved earlier.
Here is how the data gets saved: WORKS!
function saveCheckoutData() {
var vName = document.getElementById('txbx_name').value;
chrome.storage.sync.set({'name': vName}, function() {
console.log(vName);
})
}
Here is how i get the data: WORKS!
function getdata() {
chrome.storage.sync.get('name', function(data) {
var name = data.name;
if(name != null){
document.getElementById("txbx_name").value = name;
}
});
}
The code above gets called on button click and works perfectly!
But as soon I try to do this when the tab gets opened it doesn't work (the tab gets opened but there is nothing in the textbox): DOESN'T WORK!
function configAutofill(){
var newURL = "autofill_data.html";
chrome.tabs.create({ url: newURL });
chrome.storage.sync.get('name', function(data) {
var name = data.name;
if(name != null){
document.getElementById("txbx_name").value = name;
}
});
}
Does some one have an Idea why these lines do not work when creating a new tab?
Many thanks in advance.
Here's a question for you.
After creating a new tab, you access document.getElementById. Yes, but which document?
In your case, it would be the page calling create - which is not the created page.
In your case, it seems like you're opening a page that's part of the extension. Then you should just include code in it that will run on load.
You may want to check document.readyState:
if (document.readyState === "loading") {
document.addEventListener('DOMContentLoaded', getdata);
} else {
getdata();
}
If you're trying to do this with a webpage, you'll need a content script. Again, those normally execute after DOM is parsed - so just call getdata() at top level.
Using - HTML, JavaScript, JQueryMobile, Phonegap. (One page architecture, all pages are on one html page)
I have an if/else statement for user login, so the if statement directs the user to the homepage (if user/pass found in the database) which works perfectly fine, however I currently have a notification for the else statement but the issue is that after the notification it redirects the user back to the index page instead of remaining on the same page and allowing the user to try again.
What can I use to prevent the page being reloaded to another page for the else statement? I have already tried event.preventDefault(); and event.stopPropagation(); but I just get an error.
See below my current code -
function loginUser()
{
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
db.transaction(loginDB, errorCB);
}
function loginDB(tx)
{
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM SoccerEarth WHERE UserName='" + Username + "' AND Password= '" + Password + "'", [], renderList);
}
function renderList(tx,results)
{
if (results.rows.length > 0) {
navigator.notification.alert("Login Success!");
window.location = "#page4";
}
else
{
event.preventDefault();
event.stopPropagation();
/* navigator.notification.alert("Incorrect! Please try again. "); */
}
}
function renderList(event, tx, results) {
if (results.rows.length > 0) {
window.location = "#page4";
} else {
event.preventDefault();
event.stopPropagation();
/* navigator.notification.alert("Incorrect! Please try again. "); */
}
You need to pass the event in as a arguement. Then prevent the default behaviour on it by using event.preventDefault();
But I'd like to point out that you aren't using an event here, this is just checking to see if something is on the page.
The web page is displayed upon redirection from another website and the URL changes during this process to point to a different port number.
So, I would like the JavaScript to detect if the URL is correct.
If the user closes the browser/tab, display an Alert Box with warning message.
Run PHP script to close the user Session
My code is:
if (window.location.href === "http://abc123.net.au:2048 ") {
$(function () {
try {
opera.setOverrideHistoryNavigationMode('compatible');
history.navigationMode = 'compatible';
}
catch (e) {
}
function OnBeforeUnload() {
$(window).onbeforeunload;
// Post to script that will log the user out
xmlhttp.open("POST", "../logscript.php", true);
xmlhttp.send();
}
function ReturnMessage() {
return "Wait, by closing this session I will end your session. You will be required to log in again t access the site.";
}
function UnBindWindow()
{
$(window).unbind('beforeunload', ReturnMessage);
}
$(window).bind('beforeunload', ReturnMessage);
});
}
else {
document.write('<div>code is not working</div>')
}
This is the solution to your second work order:
window.onbeforeunload = bunload;
function bunload() {
dontleave = "Are you sure you want to leave?";
return dontleave;
}