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;
}
Related
I would like to automatically add an affiliate identifier to URLs on my website.
For example, I have external URLs such as:
https://www.adairs.com.au/
https://bedthreads.com.au/products/caitlin-robson-footed-bowl
My affiliate identifier varies based on the retailer, such as:
adairs.com.au: https://t.example.com/12345/t/54321?Url=
bedthreads.com.au: https://t.example.com/12121/t/21212?Url=
I need these automatically prepended at the beginning of the external URLs upon click to form:
https://t.example.com/12345/t/54321?Url=https://www.adairs.com.au/
https://t.example.com/12121/t/21212?Url=https://bedthreads.com.au/products/caitlin-robson-footed-bowl
The closest solution I have found was here however I am not very experienced in java and was unable to make it work. Ideally, I would also like to add other automatic affiliate identifiers for other retails in future.
Also, is it possible to add this in PHP?
Any help would be greatly appreciated. Thank you.
// attach a click even to all <a> elements
$("a").click(function() {
addAffiliate(this);
});
// adairs affiliate URL for redirect
var adairsaffURL = "https://t.example.com/12345/t/54321?Url=";
// bedthreads affiliate URL for redirect
var bedthreadsaffURL = "https://t.example.com/12121/t/21212?Url=";
// function called when link is clicked
function addAffiliate(link) {
// make sure this link is not to the current site and does not contain the affiliateURL
if ((link.href).indexOf(adairs.com.au) < 0 && (link.href).indexOf(adairsaffURL) < 0){
// update the link with the affiliateURL, the url encoded link, and the additional query string
link.href = affiliateURL + escape(link.href);
}else if((link.href).indexOf(bedthreads.com.au) < 0 && (link.href).indexOf(bedthreadsaffURL) < 0){
link.href = bedthreadsaffURL + escape(link.href);
}
alert(link.href);
// return true to follow the link
return true;
}
As your idea, I updated your code to let it works. Please Run code snippet to see the demo.
You just need to use .indexOf('adairs.com.au') to check the link belongs to the affiliate program, so you append it into affiliate URL.
jQuery(document).ready(function($) {
// adairs affiliate URL for redirect
var adairsaffURL = "https://t.example.com/12345/t/54321?Url=";
// bedthreads affiliate URL for redirect
var bedthreadsaffURL = "https://t.example.com/12121/t/21212?Url=";
// function called when link is clicked
addAffiliate = function(link) {
if (link.hash.substr(1).length > 0) return true;
var redirectUrl = link.href;
if (!redirectUrl || !isValidURL(redirectUrl)) return true;
if (redirectUrl.indexOf('adairs.com.au') > 0) {
redirectUrl = adairsaffURL + escape(redirectUrl);
} else if (redirectUrl.indexOf('bedthreads.com.au') > 0) {
redirectUrl = bedthreadsaffURL + escape(redirectUrl);
}
link.href = redirectUrl;
return true;
}
$("a").click(function(event) {
addAffiliate(this);
});
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
return (res !== null)
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
test adairs
<br/><br/>
test bed threads
<br/><br/>
test not match adairs or bedthreads
<br/><br/>
test no link
Update: function to add to Wordpress. Put the below into your functions.php in your theme.
add_action('wp_footer', 'auto_affiliate_url');
function auto_affiliate_url()
{
?>
<script>
jQuery(document).ready(function ($) {
// adairs affiliate URL for redirect
var adairsaffURL = "https://t.example.com/12345/t/54321?Url=";
// bedthreads affiliate URL for redirect
var bedthreadsaffURL = "https://t.example.com/12121/t/21212?Url=";
// function called when link is clicked
addAffiliate = function(link) {
if (link.hash.substr(1).length > 0) return true;
var redirectUrl = link.href;
if (!redirectUrl || !isValidURL(redirectUrl)) return true;
if (redirectUrl.indexOf('adairs.com.au') > 0) {
redirectUrl = adairsaffURL + escape(redirectUrl);
} else if (redirectUrl.indexOf('bedthreads.com.au') > 0) {
redirectUrl = bedthreadsaffURL + escape(redirectUrl);
}
link.href = redirectUrl;
return true;
}
$("a").click(function(event) {
addAffiliate(this);
});
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
return (res !== null)
};
});
</script>
<?php
}
I'm trying to reuse a button in different landing pages and change the hyperlink of this button depending on what page is being browsed.
I started my function for it but I'm stuck on how to pass the data. If the user is on a page that contains home_ns in the url, I would like the button link to be cart1 and if the user is on a page called home_nd I would like it to be cart 2.
<script type="text/javascript">
var cart1 = '/?add-to-cart=2419';
var cart2 = '/?add-to-cart=2417';
function urlCart() {
if(window.location.href.indexOf("home_ns") > -1) {
// This is where I am stuck
}
}
</script>
Then the button will be
<button onclick="urlCart()">Order Now</button>
Here is what you need:
var cart1 = '/?add-to-cart=2419';
var cart2 = '/?add-to-cart=2417';
function urlCart() {
if(window.location.href.indexOf("home_ns") > -1) {
window.location.href = cart1;
} else {
window.location.href = cart2;
}
}
You could create a look-up map of pages to cart ID. You can then update the search parameter in the URL to reflect the found ID.
Note: Since the Stack snippet below is not going to actually have the correct href, the code will not add/update the parameter. If you want to integrate this, replace the url variable declaration with this:
let url = window.location.href;
You could also use the pathname instead of the href for finer granularity.
let url = window.location.pathname;
// See: https://stackoverflow.com/a/56593312/1762224
const setSearchParam = function(key, value) {
if (!window.history.pushState) return;
if (!key) return;
let url = new URL(window.location.href);
let params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) params.delete(key);
else params.set(key, value);
url.search = params;
url = url.toString();
window.history.replaceState({ url: url }, null, url);
}
const pageMap = {
"home_ns": 2419,
"home_nd": 2417
};
function urlCart() {
let url = 'https://mywebsite.com/home_ns' || window.location.href;
Object.keys(pageMap).some(page => {
if (url.includes(page)) {
console.log('Found page:', page);
setSearchParam('add-to-cart', pageMap[page]);
return true;
} else {
return false;
}
});
}
<button onclick="urlCart()">Order Now</button>
Simply you can move the user to another page by:
location.href = myURL;
The browser will automatically go to the specified page.
Examples of what a URL can be:
An absolute URL - points to another web site (like
location.href="http://www.example.com/default.htm")
A relative URL - points to a file within a web site (like location.href="default.htm")
An anchor URL - points to an anchor within a page (like
location.href="#top")
A new protocol - specifies a different protocol
(like location.href="ftp://someftpserver.com",
location.href="mailto:someone#example.com" or
location.href="file://host/path/example.txt")
Source
I have this link http://localhost:3007/sellers-toolkit/, but the right page is only the one without a trailing slash. So I would like a redirection to http://localhost:3007/sellers-toolkit.
I tried to write this part in JavaScript, but it just makes the page reload and nothing happens. What is the right way to achieve this behavior?
var url = "http://localhost:3007/sellers-toolkit/";
if (url) {
url = "http://localhost:3007/sellers-toolkit";
window.location.href = url;
}
my solution for this issue is that i was trying to do that on the javascript side but i found that i have to do this on my node server side.
i used this code:
if (req.url == '/sellers-toolkit' || req.url == '/sellers-toolkit/' ) {
category = 'Selling Privately';
}
Try like below:
var url = "http://localhost:3007/sellers-toolkit/";
var spe_char_last =url.substr(url.length - 1);
if(spe_char_last == '/')
{
url = url.slice(0, -1);
if (url) {
url = "http://localhost:3007/sellers-toolkit";
window.location.href = url;
}
}
I developed a web application and deployed into the server and my security team come up with the below security remidiation issue.
Reflected HTML Parameter Pollution (HPP) is an injection weakness vulnerability that occurs when an attacker can inject a delimiter and change the parameters of a URL generated by an application. The consequences of the attack depend upon the functionality of the application, but may include accessing and potentially exploiting uncontrollable variables, conducting other attacks such as Cross-Site Request Forgery, or altering application behavior in an unintended manner. Recommendations include using strict validation inputs to ensure that the encoded parameter delimiter “%26” is handled properly by the server, and using URL encoding whenever user-supplied content is contained within links or other forms of output generated by the application.
Can any one have the idea about how to prevent HTML parameter pollution in asp.net
here is the script code in the webpage
<script type="text/javascript" language="javascript">
document.onclick = doNavigationCheck ;
var srNumberFinal="";
function OpenDetailsWindow(srNumber)
{
window.open("xxx.aspx?SRNumber="+srNumber+ "","","minimize=no,maximize=no,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,width=800,directories=no,resizable=yes,titlebar=no");
}
function OpenPrintWindow()
{
var querystrActivityId = "<%=Request.QueryString["activityId"]%>";
if(querystrActivityId != "")
{
var url = "abc.aspx?id=" + "<%=Request.QueryString["id"]%>" + "&activityId=" + querystrActivityId + "";
}
else
{
var hdrActivityId = document.getElementById('<%=uxHdnHdrActivityId.ClientID%>').value;
var url = "PrintServiceRequestDetail.aspx?id=" + "<%=Request.QueryString["id"]%>" + "&activityId=" + hdrActivityId + "";
}
childWinReference=window.open(url, "ChildWin","minimize=yes,maximize=yes,scrollbars=yes,status=yes,toolbar=no,menubar=yes,location=no,directories=no,resizable=yes,copyhistory=no");
childWinReference.focus();
}
function NavigateSRCopy(srNumber)
{
srNumberFinal = srNumber;
if (srNumber != "undefined" && srNumber != null && srNumber != "")
{
new Ajax.Request('<%= (Request.ApplicationPath != "/") ? Request.ApplicationPath : string.Empty %>/xxx/AutoCompleteService.asmx/CheckFormID'
, { method: 'post', postBody: 'srNumber=' + srNumber, onComplete: SearchResponse });
}
}
function SearchResponse(xmlResponse)
{
var xmlDoc;
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xmlResponse.responseText);
}
catch(e)
{
try // Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(xmlResponse.responseText,"text/xml");
}
catch(e)
{
alert(e.message);
return;
}
}
if(xmlDoc.getElementsByTagName("string")[0].childNodes[0] != null)
{
formID = xmlDoc.getElementsByTagName("string")[0].childNodes[0].nodeValue;
}
else
{
formID = null;
}
if(formID != null && formID != "")
{
window.location.href = '/CustomerSupportRequest/CreateServiceRequest.aspx?id=' + formID + '&TemplateSR=' + srNumberFinal + '&Frompage=CopySR';
return true;
}
else
{
alert("This Service Request cannot be copied because it meets at least one of these conditions: \t\t\n\n * It was created prior to 10/15/2008 \n * It was auto generated as part of the Report Requeue Process \n * It was auto generated as part of the ERA Requeue Process \n * It was not created online");
}
}
function UpdateChildCases()
{
var modalPopup = $find('modalParentChildComments');
modalPopup.show();
}
function HideParentChildPopup()
{
var modalPopup = $find('modalParentChildComments');
modalPopup.hide();
return false;
}
function HideErrorSRNumsPopup()
{
var modalPopup = $find('modalParentErrorSRNumDisplay');
modalPopup.hide();
return false;
}
function HideRetrySRNumsPopup()
{
var modalPopup = $find('modalRetrySRNumDisplay');
modalPopup.hide();
return false;
}
function RemoveParent_ChildFlag(type)
{
var childCases = document.getElementById("<%=uxHdnChildCases.ClientID %>");
var msg = "";
var btn;
if(type == "Child")
{
if(childCases.value.indexOf(',') != -1)
msg = "Are you sure you want to remove the Child flag from this Service Request?";
else
msg = "This is the only child associated to the parent case. Removing the child flag will also remove the parent flag from the associated case. Choose OK to remove the flags, or Cancel to close this dialog";
btn = document.getElementById('<%=uxRemoveChildFlag.ClientID%>');
}
else
{
msg = "Removing the parent flag from this case will also remove the child flag from all associated cases. Are you sure you want to remove the Parent flag from this Service Request?";
btn = document.getElementById('<%=uxRemoveParentFlag.ClientID%>');
}
if(btn)
{
if(!confirm(msg))
{
return false;
}
else
{
btn.click();
}
}
}
function limitTextForParentChildComments()
{
var objLblCharCount = document.getElementById('uxLblPCCharCount');
var objTxtComments = document.getElementById('<%=txtParentComment.ClientID%>');
if (objTxtComments.value.length > 1500)
{
objTxtComments.value = objTxtComments.value.substring(0, 1500);
}
else
{
objLblCharCount.innerHTML = 1500 - objTxtComments.value.length + " ";
}
setTimeout("limitTextForParentChildComments()",50);
}
function ValidateInputs()
{
var lblErrorMessage = document.getElementById('<%=lblCommentErrorTxt.ClientID%>');
var objTxtComments = document.getElementById('<%=txtParentComment.ClientID%>');
if(objTxtComments.value.trim() == "")
{
lblErrorMessage.style.display = "block";
return false;
}
}
</script>
As per OWASP Testing for HTTP Parameter pollution, ASP.NET is not vulnerable to HPP because ASP.NET will return all occurrences of a query string value concatenated with a comma (e.g. color=red&color=blue gives color=red,blue).
See here for an example explanation.
That said, your code appears to be vulnerable to XSS instead:
var querystrActivityId = "<%=Request.QueryString["activityId"]%>";
If the query string parameter activityId="; alert('xss');" (URL encoded of course), then an alert box will trigger on your application because this code will be generated in your script tag.
var querystrActivityId = ""; alert('xss');"";
I have a script that specifices that a certain element does not be shown when on a specific page. Below is the code I used:
<script type="text/javascript">
function callOnPageLoad()
{
var url = window.location.href;
if(url == "http://www.exampledomain.com")
{
document.getElementById('rolex').style.display = 'none';
}
}
</script>
However I need to put a few more url's in the if statement, what is the right way of doing this?
Many thanks
I preffer to generate associative array and then check if string is set. It can be obtained from AJAX, from different script etc. and isn't hradcoded into if
<script type="text/javascript">
var urlArray = { "http://www.exampledomain.com" : true, "http://www.exampledomain.com/foobar.html" : true };
function callOnPageLoad()
{
var url = window.location.href;
if( urlArray[url] )
{
document.getElementById('rolex').style.display = 'none';
}
}
</script>
if(url == "http://www.exampledomain.com" || url == "http://www.anotherdomain.com")
{
}
Add more conditions in the if block:
<script type="text/javascript">
function callOnPageLoad()
{
var url = window.location.href;
if(url == "http://www.exampledomain.com" || url == "anotherurl" || url == "andanother")
{
document.getElementById('rolex').style.display = 'none';
}
}
</script>
have an array of urls and iterate
function callOnPageLoad()
{
var urls = [
"http://www.exampledomain.com",
"http://www.exampledomain2.com"
];
var url = window.location.href;
for ( var i=0; i < urls.length; i++ ) {
if(url == urls[i])
{
document.getElementById('rolex').style.display = 'none';
break;
}
}
}
you can create an array of those urls and run for loop thought them, this will be more dynamic approach to your problem.
using long if statements is not advisible because you can loose a character here or a bit of logic there
If your urls point to external urls or match other patterns that you can distinguish them from other urls you can use it without an array.
function callOnPageLoad(type)
{
var url = window.location.href;
var urls=new array("http://www.exampledomain1com","http://www.exampledomain2.com");
if(url in urls){
document.getElementById('rolex').style.display = 'none';
}
}
if(url == "http://www.exampledomain.com" || url =="http://www.url2.com" || url == "http://www.url3.com") and so forth ... ?