if confirm ignores location.href - javascript

The following code reloads the page rather than the desired URL
function delFile(name,id) {
if (confirm('Are you sure you want to DELETE '+name+'?')) {
location.href='/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id ;
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id);
}
else {
return false;
}
}
In the alert, the id is shown as being added properly and the URL is correct. I can copy it from the alert, then use that text to get the right result. Other scripts on the same page that use similar location.href are working perfectly but this is the only one using confirm.
I've also tried
window.location.href = "http://stackoverflow.com";
But the page still reloads.
The triggering link is:
onClick="return delFile('Bill','1234')

The href on the triggering link is still being linked to, because delFile() only returns false if the confirm is not accepted -- that's what's causing the page reload. When the function returns true, the link fires before the redirect occurs.
You want the function to return false in all cases, so don't put the return in an else clause.
function delFile(name, id) {
if (confirm('Are you sure you want to DELETE ' + name + '?')) {
location.href = '/cgi-bin/cnc.cgi?phrsrg~038919718485478~' + id;
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~' + id);
}
return false; // always, since you always want to prevent the link's default behavior. (Could also use event.preventDefault here.)
}
test

function delFile(name,id){
if (confirm('Are you sure you want to DELETE '+name+'?')) {
/* var fullpath = better to use the full url name/link;*/
var url = '/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id;
window.open(url, '_parent');
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id);
}
else {
return false;
}
}

It looks like the delFile() function is missing the opening curly brace, so I would start by fixing that. If the issue persists, check the JS console. Also, posting a codepen would be helpful.

Related

How to get current url in jquery

I can't explain myself in title. What i want is get string between slashes. Like that:
www.example.com/foo/bar/id/1
i want to get "foo". Because i made these codes.
select: function(event, ui) {
if(window.location.href = "news/" + ui.item.slug){
window.location.href =null;
}
else
window.location.href ="news/" + ui.item.slug;
}
I have a autocomplete search field. When i clicked a result, its redirecting me to www.example.com/news/34523
In this page if i use search field again, it redirects me to www.example.com/news/news/12412 After that i got 404. But if i am not in news tab, for example www.example.com/foo its working perfecly when i use search field. I just need an if statement, if i am in news pages act like another page.
You could simply use the location.pathname property to get the part between the first and second slash and run code based on this.
console.log(window.location.pathname);
console.log(window.location.pathname.split("/")[1] === "foo");
To show that this works, here is another snippet, acting as if url was window.location:
let url = document.createElement('a');
url.href = "http://www.example.com/foo/bar/id/1";
console.log(url.pathname);
console.log(url.pathname.split("/")[1] === "foo");
The problem seems to be with your url that gets redirected. Try the below code.
select: function(event, ui) {
if(window.location.href = "/news/" + ui.item.slug){
}
else
window.location.href ="/news/" + ui.item.slug;
}

location.href could not load new location?

I need to redirect to new location when a button is clicked. I have used location.href=newloactionname.aspx but it doesn't move to new location. My code is:
function OpenUser(userID) {
location.href = 'UserRegistration.aspx?userID=' + userID;
alert(location.href)//shows only previous location
}
you can try:
window.location = 'UserRegistration.aspx?userID=' + userID;
instead...
See first if you have any javasript errors. Maybe your code does not calling OpenUser function.
Also try this:
//link click
window.location.href = "https://stackoverflow.com/";
OR
// HTTP redirect
window.location.replace("https://stackoverflow.com/");
I almost sure that you have an JS error somewhere. Press F12 on your browser.
Put an alert on the function. See if the alert appears.

How do I close the popup after I post to facebook?

On our blog we have a link where users can post our articles to their timeline. A popup opens up and the user posts to facebook, then the popup stays there and redirects to "www.oursite.com". How do we instead close the popup when the user either finishes posting or clicks on the cancel button? According to this so question it can't be done but Huffington post has figured it out but looking at their code we can't figure it out.
As an example, the facebook share button here will open up a popup and then close when you either post the article or cancel.
Here's what we have:
FB.init({appId: "90210", status: true, cookie: true});
function postToFeed() {
// calling the API ...
var obj = {
method: 'feed',
redirect_uri: 'http://www.oursite.com/',
link: 'http://www.oursite.com/',
picture: 'http://www.oursite.com/png.png',
name: 'Some title',
caption: '',
description: ''
};
function callback(response){
window.close(); // doesn't do anything
//document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
We've tried adding window.close(); in the callback (and also self.close();), tried leaving redirect_uri blank (and tried leaving redirect_uri out altogether, but it's required).
It seems that the accepted answer is no longer working due to the fact that facebook now strips anything after a hash and replaces it with post_id=xxxxx.
Solution #1 (if you trust FB not to change this in the near future):
if(window.location.search.indexOf('post_id')==1) window.close();
Solution #2 (if you want a little more insurance against change and don't mind a second file):
Create a new html file closewindow.html:
<html><body><script>window.close()</script></body></html>
and link to it in the redirect.
Redirect to http://oursite.com/#close_window. Then on your site's homepage, include something like this:
if (window.location.hash == '#close_window') window.close();.
After spending a whole day working on this problem, I have a very good solution that I'd like to share. Instead of using the SDK with FB.ui(), I have discovered that I can avoid it entirely by manually opening my own popup to https://www.facebook.com/dialog/feed. When doing it this way, redirect_uri works as expected. As long as you require the user to click a button to make the dialog pop up, no popup blocker will be triggered.
I don't believe there are any compromises with this code, and if anything, it is much easier to use than the actual SDK.
My Javascript code (which you can save as FacebookFeedDialog.js) looks like this:
/* by Steven Yang, Feb 2015, originally for www.mathscore.com. This code is free for anybody to use as long as you include this comment. */
function FacebookFeedDialog(appID, linkTarget, redirectTarget) {
this.mParams = {
app_id: appID,
link: linkTarget,
redirect_uri: redirectTarget,
display: "popup"
}
};
/* Common params include:
name - the title that appears in bold font
description - the text that appears below the title
picture - complete URL path to the image on the left of the dialog
caption - replaces the link text
*/
FacebookFeedDialog.prototype.addParam = function(key, value) {
this.mParams[key] = value;
};
FacebookFeedDialog.prototype.open = function() {
var url = 'https://www.facebook.com/dialog/feed?' + encodeCGIArgs(this.mParams);
popup(url, 'feedDialog', 700, 400);
};
/* Takes a param object like this:
{ arg1: "value1", arg2: "value2" }
and converts into CGI args like this:
arg1=value1&arg2=value2
The values and args will be properly URI encoded
*/
function encodeCGIArgs(paramObject) {
var result = '';
for (var key in paramObject) {
if (result)
result += '&';
result += encodeURIComponent(key) + '=' + encodeURIComponent(paramObject[key]);
}
return result;
}
function popup(mylink,windowname,width,height) {
if (!window.focus) return;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
if (!windowname)
windowname='mywindow';
if (!width)
width=600;
if (!height)
height=350;
window.open(href, windowname, 'resizable=yes,width='+width+',height='+height+',scrollbars=yes');
}
Here's a sample HTML file that uses the Javascript code above:
<HTML>
<BODY>
<SCRIPT type="text/javascript" src="FacebookFeedDialog.js"></SCRIPT>
<SCRIPT>
var dialog = new FacebookFeedDialog(yourAppIDGoesHere,yourDestinationURLGoesHere,yourCloseWindowURLGoesHere);
dialog.addParam('name','This is my title');
dialog.addParam('description','This is the description');
dialog.addParam('picture',yourImageURLGoesHere);
dialog.addParam('caption','This is the caption');
</SCRIPT>
Open facebook dialog
</BODY>
</HTML>
Your closeWindow html file can look like this:
<SCRIPT>
window.close();
</SCRIPT>
As of 10/2017 removing redirect_uri seems to work.
It will default to https://www.facebook.com/dialog/return/close#_=_
whose source is just
<script type="text/javascript"> window.close() </script>
UPDATE:
Add this script to your redirect page:
if (document.referrer == "https://www.facebook.com/" && (window.location.href.indexOf('post_id=') != -1 || window.location.hash == '#_=_')) {
window.close();
}
Just remove the redirect_uri parameter from the url.
Like here.
This is not a direct answer to the original question, but it might help others arriving here.
There is a more robust way to do this that allows you take action on the originating page when the share has completed successfully:
In the originating page:
var shareWindow;
function openShareWindow() {
// See https://developers.facebook.com/docs/sharing/reference/share-dialog
shareWindow = window.open('https://www.facebook.com/dialog/share?app_id=...&display=popup&redirect_uri=...');
}
function shareCompleted() {
if (shareWindow) {
shareWindow.close();
shareWindow = null;
// The share was successful, so do something interesting here...
}
}
In the page you have set as your redirect_uri, which I usually map to something like http://myserver.com/share/close:
window.opener.shareCompleted();
Now you're assured the share window will close and you'll be able to take action on the originating page if needed.
Note: shareCompleted must be available in the root window namespace for this work. If you're wrapping all of your JavaScript as you should be, then be sure to:
window.shareCompleted = shareCompleted;
<script>if (window.location.hash.indexOf("#close_window") != -1) window.close();</script>

window.location.href not working in form onsubmit

So i have a form, and onsubmit="return reg_check(this)" where reg_check() is a javascript function in the header which is supposed to check the form data, and since one of its tasks is to check if the username is in the database which requires php, i want to redirect to a php page that does this task.
Problem is: window.location.href is not working! Here's the function (reduced version) and of course the main.php is just a random page i got:
function reg_check(myForm) {
alert("before redirect..");
window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
alert("after redirect..");
}
The before redirect and after redirect alerts work, it just doesn't redirect? It remains in the same page.
Also, if I tried to redirect from the body by just typing :
<script type="text/javascript">
alert("before redirect..");
window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
alert("after redirect..");
</script>
it redirects.
Any ideas of how I could get this to work?
You need to return false; from your reg_check function and then in your onsubmit, change it to:
onsubmit="return reg_check(this);"
This will cancel the form submission. And if you want to let the form submit as normal, just return true from reg_check.
Edit (to be more clear you need to add return false; from your function):
function reg_check(myForm) {
alert("before redirect..");
window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
return false;
}
I've seen problems in IE where I've had to do the following:
window.location.assign(url);
Specifically within a jQuery AJAX success handler. Can't really speculate to why other than for me, it worked.
Actually I did
window.location.replace(url)
Which replaces the current page in the history. Nice trick that!
I had the same problem, but found the answer here Javascript: window.location.href doesn't redirect when calling function within a function .
My button was reloading the page by default so if you add an
event.PreventDefault();
To your function it should work.
[RESOLVED] I had a similar problem in redirecting to some other url from client script. Implemented window.open function instead and it worked. You may have for instance, a function say ChangeCity() for your html control event that gets called with onchange event.
function ChangeCity() {
switch ($("#currentCity").val()) {
case "NY":
var url = '#Url.Action("New York City", "Home", new { #area = "" },Request.Url.Scheme)';
window.location.href = url;
window.open(url,"_top");
return false;
/* cases for other cities */
}
You may like to explore details on window.location.href redirection -Alternative Solution

Catching A Browser Close Event

Hello Seniors (As I am new to Web Based Applications),
I was keen to implement or catching browser closing event.
Yes! I did it and successfully implemented it by using javascript{see code below}
but I have implemented it in a web page without MasterPage.
Now, as I am trying to implement it in a webpage with MASTERPAGE but in each post back...the event window.onunload is caught, which is giving me problems...
Is there any technique or logic to detect whether I can differentiate between a Close browser button and a page's post back event.
Please guide me...as I have to implement in a project as soon as possible....
thank you.
Ankit Srivastava
<script type="text/javascript">
function callAjax(webUrl, queryString)
{
var xmlHttpObject = null;
try
{
// Firefox, Opera 8.0+, Safari...
xmlHttpObject = new XMLHttpRequest();
}
catch(ex)
{
// Internet Explorer...
try
{
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(ex)
{
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ( xmlHttpObject == null )
{
window.alert('AJAX is not available in this browser');
return;
}
xmlHttpObject.open("GET", webUrl + queryString, false);
xmlHttpObject.send();
return xmlText;
}
</script>
<script type="text/javascript">
var g_isPostBack = false;
window.onbeforeunload = check ()
function check()
{
if ( g_isPostBack == true )
return;
var closeMessage =
'You are exiting this page.\n' +
'If you have made changes without saving, your changes will be lost.\n' +
'Are you sure that you want to exit?';
if ( window.event )
{
// IE only...
window.event.returnValue = closeMessage;
}
else
{
// Other browsers...
return closeMessage;
}
g_isPostBack = false;
}
window.onunload = function ()
{
if ( g_isPostBack == true )
return;
var webUrl = 'LogOff.aspx';
var queryString = '?LogoffDatabase=Y&UserID=' + '<%# Session["loginId"] %>';
var returnCode = callAjax(webUrl, queryString);
}
</script>
There is no javascript event which differentiates between a browser being closed and the user navigating to another page (either via the back/forward button, or clicking a link, or any other navigation method). You can only tell when the current page is being unloaded. Having said that, I'm not sure why you'd even need to know the difference? Sounds like an XY problem to me.
The answer can be found on SO:
How to capture the browser window close event?
jQuery(window).bind("beforeunload", function(){return confirm("Do you really want to close?") })
and to prevent from confirming on submits:
jQuery('form').submit(function() {
jQuery(window).unbind("beforeunload");
...
});
First step: add global JavaScript variable called "_buttonClicked" which is initially set to false.
Second step: have every button click assign _buttonClicked value to true.. with jQuery it's one line, pure JavaScript is also few lines only.
Third step: in your function check _buttonClicked and if it's true, don't do anything.
EDIT: After quick look in your code I see you already have steps #1 and #3, so all you need is the second step, assign g_isPostBack as true when any submit button is clicked. Let me know if you need help implementing the code and if you can have jQuery.
If one wants to catch Log out when the browser is closed (by clicking on the cross), we can take the help of window events.
Two events will be helpful: onunload and onbeforeunload.
But the problem arises that the code will also work if you are navigating from one page to another as well as also when one
refreshes the page. We don't want our sessions to be clear and inserting the record of logging out while refreshing.
So the solution is if we distinguish the difference between closing and refreshing or navigating.
I got the solution:
Write 'onbeforeunload ="loadOut();"' within the body tag on master page.
Add the following function inside script in head section of master page :-
function loadOut() {
if ((window.event.clientX < 0) || (window.event.clientY < 0))
{
// calling the code behind method for inserting the log out into database
}
}
And its done. It is working for IE, please check for other browsers. Similarly you can detect the event if the window is closed
by pressing the combination of keys ALT+F4.
window.unload fires when we navigate from one page to another as well as when we click on close button of our browser,So to detect only browser close button you need to use flag.
var inFormOrLink;
$("a,:button,:submit").click(function () { inFormOrLink = true; });
$(":text").keydown(function (e) {
if (e.keyCode == 13) {
inFormOrLink = true;
}
})/// Sometime we submit form on pressing enter
$(window).bind("unload", function () {
if (!inFormOrLink) {
$.ajax({
type: 'POST',
async: false,
url: '/Account/Update/'
});
}
})

Categories

Resources