Checking a URL in an if/else statement? - javascript

I'm trying to check a submitted URL (excluding any additional paths).
The user submitted URL is:
var inputUrl = document.getElementById("inputVal").value;
If the user submits 'http://stackoverflow.com/questions/ask' then I'm trying to create an if/else statement that will determine whether the site is 'stackoverflow.com', regardless of 'http/https' or any '/.../.../' after .com
if (inputUrl == "stackoverflow.com") {
console.log ("stackoverflow");
} else {
console.log("not stackoverflow");
}
Any help would be greatly appreciated.

if(inputUrl.toLowerCase().indexOf("stackoverflow.com") > -1) {
...
}

A little trick to have the browser do most stuff for you (can be found at MDN):
var url = document.createElement('a');
url.href = 'http://stackoverflow.com/questions/ask';
console.log(url.host); // stackoverflow.com
if (url.host == "stackoverflow.com") {
console.log ("stackoverflow");
} else {
console.log("not stackoverflow");
}
The same way you can also access other parts of the URL like protocol or hash.

$("button").on("click",function(){
var inputUrl = document.getElementById("inputVal").value;
inputUrl=inputUrl.split("http://")[1] || inputUrl.split("https://")[1] ;
inputUrl=inputUrl.split("/")[0];
if (inputUrl == "stackoverflow.com") {
console.log ("stackoverflow");
} else {
console.log("not stackoverflow");
}
}) ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="inputVal" value="http://stackoverflow.com/questions/ask">
<button>
submit
</button>
jsfiddle Demo : https://jsfiddle.net/geogeorge/h40dvbq6/2/

Related

Why my function doesn´t redirect using window.location.href?

I have a function in javascript linked to a form that check cookies and log in, so when it does all the checks and everithing is ok it shows a confirm popup and if the user clicks in ok it should link to another internal page but it doesn´t, I mean, it shows the confirm popup but it doesn´t redirect.
I have tried window.location.href and window.location.replace but nothing works.
function checkCookies() {
var emailValue = document.getElementById("nombre").value;
var passValue = document.getElementById("pass1").value;
var correct_email = checkCookie("email", emailValue);
var correct_pass = checkCookie("pass", passValue);
if (correct_email == -1) {
alert("Password or email are wrong")
} else if (correct_pass == -1) {
alert("Password or email are wrong")
} else if (correct_pass === correct_email) {
alert("Log in succesfully")
window.location.href = "principal.html";
} else {
alert("Password or email are wrong")
}
}
If you see
Log in succesfully
On the screen and then nothing happens, try to replace this line:
window.location.href = "principal.html";
with
location.assign("/principal.html");
I assume that /principal.html is in the same directory we're currently in while checking cookies or in the root.
Try
document.location.replace("principal.html").
also, what error are you getting?

Redirects page base on user country (Javascript)

I’m struggling to find a good resource on how to execute this. I wanted to redirect the page base on user location. I know this required custom code but at the moment I’m stuck with it and most of the resources that I found are outdated. I’m using ipinfo.io to determine the user country.
Here’s the code that I’m using :
$.get(“https://ipinfo.io”, function(data) {
if(data.country !== “GB”){
console.log(“no gb”)
}else {
var test
test = ‘GB’
console.log(“THIS IS GB”)}
}, “jsonp”);
But then I’m stuck on how to use those value and redirect the page.
If anyone has any experience on this please guide me :pray:t3:
To redirect use location.href
$.get('https://ipinfo.io', function(data) {
if(data.country !== “GB”){
location.href = 'http://ADDRESS-TO-GB'
} else {
location.href = 'http://ADDRESS-TO-ANYWHERE'
}, 'jsonp');
$(function(){
$.get( "https://ipapi.co/json/", function( data ) {
switch(data.country){
case 'US':
window.location = 'http://www.google.us';
break;
case 'KR':
window.location = 'http://www.google.kr';
break;
default:
window.location = 'http://www.google.com';
break;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
you can use a switch case to do redirection base on the callback received data.
try this one
$.getJSON('https://ipinfo.io', function(data) {
if(data.country == 'America'){
location = 'your_redirect_url';
return;
}else if(data.country == 'Beijing'){
location = 'your_redirect_url';
return;
}
})
you can use $.getJSON function then location.href to redirect.
$.getJSON( "https://ipapi.co/json/", function( data ) {
if(data.country !== "GB"){ location.href="your site url"}
if(data.country !== "US"){location.href="your site url"}
});

use the URL to press the "accept" Button (javascript) automaticaly while call a webpage

I've build a javascipt code that popup's a policy which a visitor has to accept.
This is working fine but now I will use some systemAccounts and they will not accept this on their own.
Now I hope that I can find a solution in customizing my URL String. I want to creat a "https://www.url.de/xyz/?pressButtonAutomaticaly?goToNextPage" String
I hope you can give me a hint, all I found was about "createButton"
Here is the code:
<script type="text/javascript">
function getConfirmation(){
var retVal = confirm("Do you want to continue by accepting Policy ?");
if( retVal == true ){
document.write ("User wants to continue!");
// window.location = "URL";
window.location = "URL";
return true;
}
else{
document.write ("You have Not Accepted Download Policy!");
window.close();
return false;
}
}
</script>
Thank you and best wishes,
Nils
You can use the window.location.search property to check if your query string parameters are there and then take action accordingly.
Would something like this work for your needs better?
function continueOn() {
document.write("User wants to continue!");
window.location = "URL";
return true;
}
function getConfirmation() {
var retVal = confirm("Do you want to continue by accepting Policy ?");
if( retVal == true ){
return continueOn();
}
else{
document.write ("You have Not Accepted Download Policy!");
window.close();
return false;
}
}
function autoClickButton(queryString) {
if (queryString.indexOf('pressButtonAutomatically') > -1) {
return true;
}
else {
return false;
}
}
function init(queryString) {
if (autoClickButton(queryString)) {
continueOn();
}
else {
document.getElementById('button').addEventListener('click', getConfirmation);
}
}
init(window.location.search);

Excute jquery if url is home page

I need to fire piece of jQuery code only if it is home page.
URL probability are
http://www.example.com
http://www.example.com/
http://www.example.com/default.aspx
How can i run code if it is any of the above url i can use
var currenturl = window.location
but then i have to change this every time i move my code to server as on local host my url is like
http://localhost:90/virtualDir/default.aspx
in asp.net we can get the it using various
HttpContext.Current.Request.Url.AbsolutePath
or
HttpContext.Current.Request.ApplicationPath
I am not sure what are the equivalent in jQuery
reference of asp.net example
UPDATE:
I have taken a simple approach as i could not find other easy way of doing it
var _href = $(location).attr('href').toLowerCase()
var _option1 = 'http://localhost:51407/virtualDir/Default.aspx';
var _option2 = 'http://www.example.com/Default.aspx';
var _option3 = 'http://www.example.com/';
if (_href == _option1.toLowerCase() || _href == _option2.toLowerCase() || _href == _option3.toLowerCase()) {
$(".bar-height").css("min-height", "689px");
// alert('aa');
}
else
{ //alert('bb'); }
Could you only include the script on the page where it's needed? i.e. only use <script type="text/javascript" src="homepage.js"></script> from default.aspx ?
If not, then, as dfsq said - use window.location.pathname .
var page = window.location.pathname;
if(page == '/' || page == '/default.aspx'){
// -- do stuff
}
You could just get the part after the last slash, to account for folder differences...
var page = window.location.toString();
page = page.substring(page.lastIndexOf('/'));
... but this would be true for both example.com/default.aspx and example.com/folder1/default.aspx.
Remember, this Javascript is client-side, so there's no equivalent to the C# example you linked.
You could use my approch to know exactly the page (also with urlrouting) to use it in javascript:
I use the body id to identify the page.
javascript code:
$(document).ready(function () {
if (document.body.id.indexOf('defaultPage') == 0) {
/*do something*/
}
});
Asp.net code:
in masterpage or page (aspx):
...
<body id="<%=BodyId %>">
...
code behind:
private string _bodyId;
public string BodyId
{
get
{
if (string.IsNullOrWhiteSpace(_bodyId))
{
var path = GetRealPagePath().TrimStart('/','~');
int index = path.LastIndexOf('.');
if (index > -1)
{
path = path.Substring(0, index);
}
_bodyId = path.Replace("/", "_").ToLower();
}
return string.Concat(_bodyId,"Page");
}
}
public string GetRealPagePath()
{
string rtn = Request.Path;
if (Page.RouteData != null && Page.RouteData.RouteHandler!= null)
{
try
{
if (Page.RouteData.RouteHandler.GetType() == typeof(PageRouteHandler))
{
rtn=((PageRouteHandler)Page.RouteData.RouteHandler).VirtualPath;
}
else
{
rtn = Page.Request.AppRelativeCurrentExecutionFilePath;
}
}
catch (Exception ex)
{
Logger.Error(string.Format("GetRealPagePath() Request.Path:{0} Page.Request.AppRelativeCurrentExecutionFilePath:{1}", Request.Path, rtn), ex);
}
}
return rtn;
}

Javascript not redirecting

I have searched extensively for the javascript code to redirect to a different page on the same site and in the same folder and I have tried numerous things. I'm unable to get it to work in localhost or on the web-server. This is what I've tried:
<script type="text/javascript">
function confirm_submit()
{
var con = confirm("Submit form and print invoice?");
var url = 'dashboard.php?del=no';
if (con == true) {
document.location.href = url;
/*I have also tried:
window.location = 'dashboard.php?del=no';
window.location.replace("dashboard.php?del=no");
window.location.href = "dashboard.php?del=no";
*/
}
else {
return false;
}
}
</script>
This is the code on the button :
onclick="return(confirm_submit())"
From everything I've read this should work but it is not working. Can someone please tell me why it is not working and what I need to do to make it work? Thank you in advance.
EDIT: I have answered the question below. It's a workaround, but it is doing the job.
this will work without submitting your form
var url = window.location.href;
splitUrl = url.split("/");
splitUrl[splitUrl.length-1]="your page";
url = splitUrl.join("/");
window.location.href = url;
I have spent too much time on this issue so I have decided to go a different route. I'm using javascript to change the value of a hidden field and then using PHP to redirect to the other page as a result of the posted value of the hidden field. Thanks to all who have given their time to this matter on my behalf. Cheers
<script type="text/javascript">
function confirm_submit()
{
var con = confirm("Submit form and print invoice?");
if (con == true) {
document.getElementById('bool').value = true;
$("#edit_workorder").submit();
}
else {
return false;
}
}
</script>
And the PHP is:
if($bool == true) {
header("Location:dashboard.php?del=no");
exit;
}
It's doesn't really answer the question, but it works and that is more important to me right now.

Categories

Resources