Trigger function based on result of custom function Referring URL - javascript

I need to use JavaScript (jQuery if applicable) to trigger my modal call if the result of my function is true and the referring URL is not of the domain.
The desire is that the user visits the main splash page and as long as they have not been redirected there by the site itself (via timeout on a session, invalid login credentials, etc) it displays the message so:
function showModalIf() {
if (checkFunction) {
if(////// REFERRING URL not from this site)
Trigger Modal Call
else
Don't Do anything else
}
}

Assuming you use jQuery UI Dialog to show the modal
function checkReferrerExternal() {
if (!document.referrer || document.referrer == '') return false;
var regex = /^https?:\/\/\/?([^?:\/\s]+).*/;
var referrermatch = regex.exec(document.referrer);
var locationmatch = regex.exec(document.location);
return referrermatch[1] != locationmatch[1];
}
function showModalIf() {
if (checkReferrerExternal()) {
//show jQuery UI Dialog modal or replace with whatever
$("div#dialog").dialog('open');
}
}
Check demo page http://jsbin.com/efico

If you are talking about forced redirection in the code, and not just a hyperlink click from elsewhere in the site, you could add a query string parameter on your redirection and check that way. Another option is to set a cookie and check for the cookie in javascript.
Here is a nice link on cookie handling in Javascript:
Javascript - Cookies
And here's one for parsing query string params/hashes in Javascript as well:
Parsing The Querystring with Javascript
Hope this points you in the right direction :)

Related

Need to navigate users to landing page when browser back button is pressed

I have a ASP.net MVC web application which consists of several pages. The requirement is like this:
when users are using the application, suppose user is in page 7, suddenly user navigates away from the application by typing a external internet URL say Google.com.
Now when user presses the back button of the browser, Instead of bringing him back to page 7, we need to redirect him to Page 0 which is the landing page of the application.
Is there any way to achieve this? we have a base controller which gets executed every time a page loads as well as a master page (aspx). Can we do something there so that this behavior can be implemented in all the pages?
I think the best solution is to use iframe and switch between your steps inside of iframe. It would be quite easy to do, because you don't need to redesign your application. Anytime when user tries to switch to other url and come back, the iframe will be loaded again from the first step.
Be sure to disable caching on every step of your application. You can do this by applying NoCache attribute to your controller's actions:
public class NoCache : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuting(filterContext);
}
}
There is 2 case over here
First is browser in online mode, in this case you have to store your last page get request in session, if user hit back button it will re initiate get request for that page again you can trap it and send them to landing page, You have to take care that get request for page happen only once other action must be post.
Second is browser in offline mode, in this case you have to take care that your response should not put any cache foot print in browser, there are many code example you can found on net for this purpose.
I can offer the following idea:
When user press <a href='external url' onclick='clearHistory'>link</a>
You can save in browser history of the desired url:
<script>
function clearHistory()
{
var reternUrl = getReternUrl();
History.pushState({}, null, reternUrl);
}
</script>
more about history.js
Edit: ok, then handle beforeunload event:
$(window).on('beforeunload', function () {
var reternUrl = getReternUrl();
History.pushState({}, null, reternUrl);
});
EDIT: Shortened and slightly changed code to better answer exact question (based on first comment to this answer)
Addition to answer above about editing the browser history for the case where the user types the external URL in the browser address bar.
You could try to detect url change as posted in How to detect URL change in JavaScript.
Example of this using jquery (taken and edited slightlyfrom post linked to above):
For newer browsers:
$(window).bind('hashchange', function() {
/* edit browser history */
});
For older browsers:
function callback(){
/* edit browser history */
}
function hashHandler(callback){
this.oldHash = window.location.hash;
this.Check;
var that = this;
var detect = function(){
if(that.oldHash!=window.location.hash){
callback("HASH CHANGED - new hash" + window.location.hash);
that.oldHash = window.location.hash;
}
};
this.Check = setInterval(function(){ detect() }, 100);
}
hashHandler(callback); //start detecting (callback will be called when a change is detected)
I'll get back to you on bookmarks (still need to check that out).

why is my window.dialogArguments undefined

I need to open up a .aspx page in a modal dialog. Here is the JS code I use to open the dialog:
if (url) {
var fullPath = url + "/Validation.aspx";
}
else {
alert("Could not find the location of the merge dialog. Please contact your System admin and have them update the configuration entity.");
return;
}
var features = "unadorned:yes;scroll:yes;resizable:yes;status:yes;dialogHeight:480px;dialogWidth:480px;";
var args = {
selected: selectedIds,
page: pageIds,
fetchXml: xml,
entity: "xyz"
};
window.showModalDialog(fullPath, args, features);
In my validation.aspx page I need to be able to grab the JS arguments, assign them to hidden fields, then repost, so I can use those arg values server side.
here is my JS code in my .aspx page:
window.onload = function(){
if (!window.dialogArguments)
return;
var args = window.dialogArguments;
...
}
I have seen tons of examples of this working throughout the web. But...My window.dialogArguments is always undefined in my .aspx page. What gives? anyone have any thoughts or solutions?
My assumption here is that the ASPX dialog page is being opened cross-domain.
This would mean that your parent page is in one domain aka: http://abc/page.html, and that your child dialog page is in another domain like: http://def/dialog.html.
If this is the case, it seems as though there are restrictions against accessing dialogArguments and returnValue. Check out the comments on this previous answer for example.

passing data from authentication cookie to javascript

I am using an authentication cookie passed between websites on the same domain. The cookie contains some user info and page info (the accession number). The design goal is for the user to click a button on the referring website, and it will launch a second website, authenticate based on the cookie, and do some useful stuff with the accession number. I got most of this built, including getting the authentication passed and properly parsed out on the receiving system.
The problem I am having is that I can't get the data within the cookie into the javascript on the page. It seems when i launch website2 from website1, $(document).ready() is not fired after the page_load event (which handles the cookie parsing). Also I tried using a literal to post the javascript code, it's never fired (seemingly it places it after the client side stuff is executed.
What I really want to do is call a javascript function getResults(accnum) using this data.
I have this code on the page_load event:
if (userdata != null)
{
accnum = userdata[4];
}
if (accnum != String.Empty)
{
//HttpCookie accnumcookie = new HttpCookie("accnum", accnum);
//this.Context.Response.Cookies.Set(accnumcookie);
}
}
When I run the .Set function, I'm not really sure of the innards and details, but long story short, the cookie is set but does nothing.
This is the document.ready.
$(document).ready(function () {
var accnum = new String();
accnum = GetCookie('accnum');
if (accnum != null) {
document.cookie = 'test=testz';
var srch = document.getElementById('crit');
srch.style.display = 'none';
getResults('', 'accnum', accnum);
}

How to enable Javascript to control Phonegap Childbrowser?

I use the Phonegap Childbrowser for oAuth 2.0 authentication. After the authentication, I want to use Javascript in the web page to hide the Childbrowser without pressing the "done" button. How to do that?
For example, after authentication, we always get some callback parameters. That means our authentication is successful. At this time, we should close our browser, and I want to close the browser by Javascript without pressing any buttons.
Capture onLocationChange on childBrowser and check the url parameter to see if it contains what you're looking for. If so, call childBrowser.close().
One weirdness of ChildBrowser is that it doesn't have a .clear() method, so I've created a page called nothing.html that is blank. If you don't, you'll briefly see your auth page the next time you use ChildBrowser. This doubles as my redirectUrl for Facebook and Twitter auth. So when it gets to that page, I know it's time to close.
var URL_NOTHING = 'nothing.html';
window.plugins.childBrowser.onLocationChange = function ( url ) {
if ( url.indexOf( URL_NOTHING ) > -1 ) {
if ( url.indexOf( 'oauth_token' ) > -1 ) { //twitter
window.plugins.childBrowser.close();
//do twittery stuff
} else { //facebook
window.plugins.childBrowser.close();
//do facebooky stuff
};
};
};
ChildBrowser plugin has a close() method to close the window from javascript code.
window.plugins.childBrowser.close();

Response.Redirect AFTER call to JS Alert or Confirm

I am working on a VB.NET web application. When someone successfully changes their password I want to show a popup message that lets them know it was changed successfully. After they click OK I want to redirect them to the main page. Code looks like this:
ClientScript.RegisterStartupScript(Me.GetType(), "confirmScript", "ConfirmNewUser();", True)
Response.Redirect("MainPage.aspx")
Why does the redirect happen and the alert popup never displays?
Try this:
1) Remove Response.Redirect from the code behind.
2) Change the ConfirmNewUser function as given below:
function ConfirmNewUser(){
//Existing Code of ConfirmNewUser
//New Code.
var msg = "Password changed successfully. Press OK to go to Home page Cancel to stay on current page.";
if(confirm(msg)){
window.location.href = "MainPage.aspx";
}
}
You are calling the redirect server side, your script never get a chance to run. use window.location to do the redirect client side, something like this:
function ConfirmNewUser() {
if(confirm("Your password has been changed, click OK to continue")) {
window.location = "MainPage.aspx"; //go to home page
}
}
The reason is because all server-side processing will take place prior to client-side.
One solution would be to pass "MainPage.aspx" to your client script as follows:
ConfirmNewUser('MainPage.aspx');
Your client script would then have to take a URL parameter:
function ConfirmNewUser(url) { ... }
and follow up with a window.location:
...
if(confirm(...))
{
window.location = url;
}
and remove the following from your server code:
Response.Redirect("MainPage.aspx")
Response.Redirect sets the Location http header and a 302-Moved response, the browser will act upon this as soon as it sees it. As headers come before content, your script is never seen or parsed.

Categories

Resources