multiple links in if statement - javascript

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 ... ?

Related

Automatically prepend affiliate identifier to URLs

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
}

Urls in creating chrome extension tabs do not work

I am creating a chrome extension which access a api and parses the json feed to get data. One of the data is a link and I want the link to be opened in a new tab. I use chrome.create.tabs to do it. But instead of opening a tab with specified url it opens like this
chrome-extension://app_id/%22http://www.twitch.tv/imaqtpie%22
Here is my popup.js
document.addEventListener('DOMContentLoaded', init);
function init(){
var elem = document.getElementById('Add');
elem.addEventListener('click',func);
}
function func(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.twitch.tv/kraken/search/streams?q=league%20of%20legends", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// innerText does not let the attacker inject HTML elements.
var qtpie=JSON.parse(xhr.responseText);
var display_name = JSON.stringify(qtpie.streams[0].channel.display_name);
var stream_status = JSON.stringify(qtpie.streams[0].channel.status);
var stream_url=JSON.stringify(qtpie.streams[0].channel.url);
var res = display_name+" : "+stream_status+"\n"+stream_url;
console.log(stream_url);
var a = document.createElement('a');
var linkText = document.createTextNode(res);
a.appendChild(linkText);
a.setAttribute('href', stream_url);
a.addEventListener('click', link_handler(stream_url));
document.getElementById("status").appendChild(a);
var magic=activateLinks();
// document.getElementById("status").innerText = res;
}
}
xhr.send();
}
function activateLinks()
{
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
(function () {
var ln = links[i];
var location = ln.href;
ln.onclick = function () {
chrome.tabs.create({active: true, url: location});
};
})();
}
}
function link_handler(url)
{
// Only allow http and https URLs.
if (url.indexOf('http:') != 0 && url.indexOf('https:') != 0) {
return;
}
chrome.tabs.create({url: url});
}
Here stream_url is the variable that stores the parsed url from json.
here is the json from which it is parsed from
"video_banner":null,
"background":null,
"profile_banner":null,
"profile_banner_background_color":null,
"partner":true,
"url":"http://www.twitch.tv/imaqtpie",
"views":91792487
i want the new tab to open http://www.twitch.tv/imaqtpie instead of chrome-extension://app_id/%22http://www.twitch.tv/imaqtpie
. Thanks in advance. Btw using <base href="http://" target="_blank"> does not work.
So the problem is for the url. Your url is improper when using chrome.tabs.create, because %22 indicates the character " in ASCII Encoding Reference. You should strip it off in the url when you get the element in html. Glad it helps!

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;
}

Removing %20 from fullname Aweber

Passing variables from Aweber to wordpress Thank you page - However the name appears as follows:
firstname%20Lastname
code used
<script type="text/javascript">
var formData = function() { var query_string = (location.search) ? ((location.search.indexOf('#') != -1) ? location.search.substring(1, location.search.indexOf('#')) : location.search.substring(1)) : '';
var elements = [];
if(query_string) {
var pairs = query_string.split("&");
for(i in pairs) {
if (typeof pairs[i] == 'string') {
var tmp = pairs[i].split("=");
var queryKey = unescape(tmp[0]);
queryKey = (queryKey.charAt(0) == 'c') ? queryKey.replace(/s/g, "_") : queryKey;
elements[queryKey] = unescape(tmp[1]);
}
}
}
return {
display: function(key) {
if(elements[key]) {
document.write(elements[key]);
}
else {
document.write("<!--If desired, replace everything between these quotes with a default in case there is no data in the query string.-->");
}
}
}
}
(); </script>
then
<script>// <![CDATA[
formData.display('fullname')
// ]]></script>
tried
decodeURI(formData.display("fullname"))
But it doesn't work???
I've searched and searched and cant figure it out - Please anyone help???
Thanks.
Im guessing its part of a Wordpress plugin, so you just want a fix right :)
Try replacing this part:
return {
display: function(key) {
if(elements[key]) {
document.write(elements[key]);
} else {
document.write("<!--If desired, replace everything between these quotes with a default in case there is no data in the query string.-->");
}
}
}
With this:
return {
display: function(key) {
if(elements[key]) {
document.write(decodeURIComponent(elements[key]));
} else {
document.write("<!--If desired, replace everything between these quotes with a default in case there is no data in the query string.-->");
}
}
}

How to dynamically read RSS

I want to read multiple RSS feeds using jQuery.
I'm trying to write a flexible function that will just take the RSS URL and it will output only its TITLE AND IMAGE how to do that for multiple RSS URLs?
The easiest way would be to use the Google AJAX Feed API. They have a really simple example, which suits what you want nicely:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
</script>
<div id="feed"></div>
Of course, you can mix jQuery with the API instead of using native DOM calls.
Have you seen this JQuery plug-in: http://plugins.jquery.com/project/jFeed
A little late to the party but I actually did something similar to this using the deviantART gallery feed and displaying the latest thumbnail. I wrapped it up into a couple of functions for easy use:
function keratin_callback(elem, data)
{
if (!data
|| !data.entries
|| data.entries.length < 1
|| !data.entries[0].mediaGroups
|| data.entries[0].mediaGroups.length < 1
|| !data.entries[0].mediaGroups[0].contents
|| data.entries[0].mediaGroups[0].contents.length < 1
|| !data.entries[0].mediaGroups[0].contents[0].thumbnails
|| data.entries[0].mediaGroups[0].contents[0].thumbnails.length < 1) {
$("<span>Data returned from feed not in expected format.</span>").appendTo(elem);
return;
}
var entry = data.entries[0];
$("<img>").attr("src", entry.mediaGroups[0].contents[0].thumbnails[0].url)
.appendTo(elem)
.wrap("");
}
function keratin(elem, url)
{
//keratin written by adam james naylor - www.adamjamesnaylor.com
if (!elem || elem.length < 1) return; //no element found
$.ajax({
//you could use document.location.protocol on the below line if your site uses HTTPS
url: 'http:' + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url + '&cache=' + Date.UTC()),
dataType: 'json',
success: function(data) {
if (!data || !data.responseData) {
return keratin_callback(elem, null);
}
return keratin_callback(elem, data.responseData.feed);
}
});
}
$(document).ready(function() {
keratin($('#da_gallery'), 'http://backend.deviantart.com/rss.xml?q=gallery%3Adeusuk%2F28671222&type=deviation')
});
Full details here: http://www.adamjamesnaylor.com/2012/11/05/Keratin-DeviantART-Latest-Deviation-Widget.aspx

Categories

Resources