Two URL's in function using "window.location.href" - javascript

I'm using a Marketo Embed for which allows me to add to it when I use it.
My goal is to use the "window.location.href" function to open the first URL (a .zip file) and then open a new URL (a page).
It's only using one of the URLS. Either one will work properly if they are the only one if the function. Otherwise it only fires the latter one. I've tested it and it all appears to be right, but it think I'm missing something about the rules with using window.location.href twice.
Here is my code:
<script src="//app-sj01.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_1198"></form>
<script>MktoForms2.loadForm("//marketo.com", "000-000-000", 0000, function(form) {
form.onSuccess(function(values, followUpUrl) {
window.location.href = "************.zip";
window.location.href = ".../page.html";
return false;
});});
</script>

try
<script src="//app-sj01.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_1198"></form>
<script>
MktoForms2.loadForm("//marketo.com", "000-000-000", 0000, function(form) {
form.onSuccess(function(values, followUpUrl) {
var pid = window.setInterval(function() {
window.location.href = ".../page.html";
typeof pid !== 'undefined' && window.clearInterval(pid);
}, 1000);
window.location.href = "************.zip";
return false
;});
});
</script>

Related

Use window.onbeforeunload to avoid double clicking

I tried to override window.onbeforeunload to avoid double submitting while redirecting pages.
window.onbeforeunload = disableCurrentWindow;
function disableCurrentWindow()
{
console.log("Before Disable the contents");
window.document.body.disabled = true;
console.log("After Disable the contents");
return undefined;
}
If I return true here it will give default confirmation pop up which I don't need at the moment. I just need to redirect users to next page. But no need to allow double click
If you want to disable double submit GET requests you can try to update href param in each link for short period of time right after click.
For example,
var clickedAt = null;
$(document).ready(function() {
$('a').click(function() {
if (!clickedAt) {
console.log('click allowed, destination: ' + $(this).attr('href'));
clickedAt = new Date();
$('a').each(function() {
$(this).attr('data-href', $(this).attr('href'));
$(this).attr('href', '#');
});
}
else {
console.log('click masquaraded, destination: ' + $(this).attr('href'));
}
return false;
});
});
setInterval(function() {
if (typeof $ == 'undefined') return false;
if (clickedAt && new Date().getTime() - clickedAt.getTime() > 1000) {
$('a').each(function() {
$(this).attr('href', $(this).attr('data-href'));
});
clickedAt = null;
}
}, 100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
data value
But I don't think - that you should do this. Double clicking is not a problem in most cases - it's not a DDOS for your web-server (if you see, that double clicks make a lot of load for your web-server - you should reconfigure it, because on production mode, load in any case will be more powerful).
BTW I have used data-href for dumping old href. If you are using those attributes - you can choose another one buffer.
P.S. If your page has a lot of links it can do some very small lags for your customers

script to redirect if the url contains a querystring

SHORT: Need a script to remove the parameters on URL IF EXIST. Must be jquery/Script/
LONG: I have a site where I send traffic to with lots of parameters. These are processed instantly with php to cookies. After my cookie set I would like to refresh the same page but WITHOUT parameters. I cannot do it php since the cookies need to be processed by an iframe so I need a jquery/script to do it AFTER cookies are set via the iframe.
Thanks guys! :)
The below code will remove the query string parameter and will reload the page
window.location.href = window.location.protocol+"//"+window.location.hostname+window.location.pathname
The search attribute of window location describes the GET parameters on the url so -
if (window.location.search != "") {
window.location.search = "";
}
You may want to check out this question for a another solution.
And have a look at the MDN Documentation on window.location for more info.
I think you need to use something like:
var url_update= false;
var stripped_url;
function removeparametersFromURL(url_string) {
if (url_string.indexOf("#") > 1) {
URL = url_string.split("#")[0];
url_update= true;
}
if (url_string.indexOf("?") > 1) {
URL = url_string.split("?")[0];
url_update= true;
}
return URL;
}
var stripped_url = removeparametersFromURL(top.location.href);
if(url_update){
top.location.href = stripped_url;
}
setTimeout(function(){
stripped_url = removeparametersFromURL(top.location.href);
if(url_update){
top.location.href = stripped_url;
}
},5000); //will call function after 5 seconds

JS: incrementing pages (page1.html, page2.html,page3.html...) for window.replace

What approach should for this scenario. I want the page to go to the next page after it finishes all the function it needs to.
so, example. after all function for page1.html has been done, it will call a function next_page().
next_page() function will evaluate the current page and add "1" it. so from page2.html it will now be page3.html. page3.html will also contain the same function of the previous html, that after all the functions have been done, it will call the next_page() function that will also evaluate the current and increment it.
//current_url = "mysite.com/page1.html"
var current_url = window.location;
var end_page = "mysite.com/page12.html"
var increment_url = eval(current_ur + 1 );
if(current_url != end_page ) {
setTimeout(next_page,2000)
}
else {
alert("this is the last page!")
}
function next_page() {
window.location.replace(increment_url);
}
var increment_url = addone('mysite.com/page1.html');
returns mysite.com/page2.htm
function addone(url) {
var pattern=new RegExp("(.*)([0-9+])(\..*)");
var match=pattern.exec(url);
return match[1] + (parseInt(match[2]) + 1 ) + match[3];
}
​
so assuming the example URL you gave is accurate enough that the regular expression will work use
var increment_url = addone(current_url);
The easiest thing to do would be to have a hidden input on each page that has the value of the next page url. This would allow you to use arbitrary page urls and still be able to get the effect you want.
Using jQuery
$(function() {
setTimeout(function() {
var url = $('#next_page_url').val();
window.location.replace(url);
}, 2000);
});
<input type="hidden" id="next_page_url" value="http://mysite.com/page2.html" />

jQuery add target="_blank" for outgoing link

I need some help to create jquery script :)
I have some of link like this on my HTML.
Google
Home
Home
Contact Us
And now i want jQuery to check all of the link on my page. if that link is outside of my server (my server is gusdecool.com). Then add target="_blank". and the result will be like this
Google
Home
Home
Contact Us
assuming that all external links will start with http:// you could do this:
$('a[href^="http://"]').not('a[href*=gusdecool]').attr('target','_blank');
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
$(this).attr("target","_blank");
}
});
This was from css-tricks.com, seems to work pretty well.
$('a[href^=http]:not([href^=http://www.gusdecool.com/])').attr('target','_blank');
Of course, this works only if all the external links start with the http protocol. You should adapt this code to suite your needs (suchs as links without protocols, or with different protocols).
UPDATE :
$('a[href^=http]:not([href^=http://www.gusdecool.com],[href^=http://gusdecool.com])')
.add('a[href^=www]:not([href^=www.gusdecool.com])')
.attr('target','_blank');
It selects all the a elements that have their href attribute starting with a web page address (with or without protocol) and do not point to your site's address and changes their target attribute to _blank.
This function seems to be easier if you have a subdomain:
$('a').attr('target', function() {
if(this.host == location.host) return '_self'
else return '_blank'
});
jQuery(document).ready(function(){
target_luar();
});
function target_luar(){
try{
if(top.location != location) {
jQuery("a[href^='http']")
.not("[href*='"+location.host+"']")
.attr('target','_blank');
}
} catch(err) { }
}
Demo : Demo jQuery External Link
Global function to open external links in a new window:
$(function(){ // document ready
$("a").filter(function () {
return this.hostname && this.hostname !== location.hostname;
}).each(function () {
$(this).attr({
target: "_blank",
title: "Visit " + this.href + " (click to open in a new window)"
});
});
});
Putting it all together we get the following.. Wait for it all to load, select only links starting with http or https, check if the link point to the same domain (internal) or another domain (external), add appropriate target if match found..
$(window).load(function() {
$('a[href^="http"]').attr('target', function() {
if(this.host == location.host) return '_self'
else return '_blank'
});
});
You could use jQuery's $.each function to iterate over all Anchor tags, perform the needed check and set the "target" attribute using $(this).attr("target","_blank");
Example (Not tested but should work):
$('a').each(function(index) {
var link = $(this).attr("href");
if(link.substring(0,7) == "http://")
$(this).attr("target", "_blank");
});
Shai.
Here's a fiddle demonstrating an answer using raw JS (not jQuery): http://jsfiddle.net/Xwqmm/
And here's the code:
var as = document.getElementsByTagName('a');
var re = /^https?:\/\/([^\/]*)\//;
for (var i = 0, l = as.length; i < l; i++) {
var href = as[i].href;
var matches = href.match(re);
if (matches[1] && matches[1] != "gusdecool.com") {
as[i].setAttribute("target","_blank");
}
}
This is such a brilliant site I learned so much from it :
If you do it this way you do not need to worry about http or https (handy while developing)
$('a[href^="http"]')
.not('a[href*='+ location.hostname +']')
.attr('target','_blank');
You can see all external link whith http and https
jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").each(function() {
console.log(jQuery(this).attr('href'))
});
And you can add _blank like this
jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").attr('_target','blank');
You could use filter -
$("a").filter(function () {
return this.indexOf('http://') > -1 && this.indexOf('gusdecool') == -1
}).attr("target","_blank");
Check each linkobject $(link).attr("href"), if that starts with http:// then its an outgoing link (?). Then assign the .attr("target", "_blank").
$(a).function(){
if($(this).attr("href").substring(0,3) == "http" && <!-- CHECK ITS NOT YOUR SITE URL -->){
$(this).attr("target", "_blank");
}
};
Hope this helps.
Try:
$('a[href^="http://"]')
.not('a[href*='+ location.hostname +']')
.attr('target','_blank');
<div id="myLinks">GoogleHomeHome
Contact Us</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#myLinks a').attr('target', '_blank');
});
</script>

How to use jQuery click event to change href value asynchronously, based on a JSON query

I'm using the bit.ly url shortening service to shorten certain url's being sent to a "share on twitter" function. I'd like to load the bit.ly url only when a user actually presses the share button (due to bit.ly's max 5 parallel reqs limitation). Bit.ly's REST API returns a JSON callback with the shortened url, which makes the whole scenario async.
I've tried the following to stop the click event, and wait for the JSON call to return a value before launching the click.
I have the following simplified code in jQuery(document).ready():
Updated code (oversimplified)!
jQuery("#idofaelement").click(function(event) {
event.preventDefault(); //stop the click action
var link = jQuery(this);
bitlyJSON(function(shortUrl) {
link.attr("href", function() {
//process shortUrl
//return finalized url;
}).unbind().click();
});
});
And the following code to handle the bitly shortening (works just fine):
function bitlyJSON(func) {
//
// build apiUrl here
//
jQuery.getJSON(apiUrl, function(data) {
jQuery.each(data, function(i, entry) {
if (i == "errorCode") {
if (entry != "0") {
func(longUrl);}
} else if (i == "results") {
func(entry[longUrl].shortUrl);}
});
});
} (jQuery)
The href gets its value changed, but the final .click() event never gets fired. This works fine when defining a static value for the href, but not when using the async JSON method.
As you outlined yourself:
event.preventDefault(); //stop the click action
That means, BROWSER IS NOT GOING TO THAT URL, if you wish to actually go forward to the long-url location, simply do something like:
document.location.href = longurl;
iirc, jquery doesn't trigger "click" on A elements. I'd try old good "location.href=whatever" in the callback.
bitlyJSON(function(shortUrl) {
link.attr("href", function() {
//process shortUrl
//return finalized url;
});
location.href = link.attr("href");
});
I think what you actually want is to return false; from the click event, to prevent the actual following of the href, right?
Like:
jQuery("#idofaelement").click(function(event) {
//event.preventDefault(); //stop the click action
var link = jQuery(this);
bitlyJSON(function(shortUrl) {
link.attr("href", function() {
//process shortUrl
//return finalized url;
}).unbind().click();
});
return false;
});
#Tzury Bar Yochay pointed me in the right direction by suggesting I use location.href to update the url. Also #Victor helped with his answer.
I got things kinda working combining the answers, but had issues with the history in firefox. Seems that updating window.location indeed redirected the user, but also removed the "source page" from the history. This did not happen in chrome, safari, ie8, ie8-compatibility or ie7.
Based on this response to another question I was able to create a workaround giving the following working code + made a few changes:
jQuery("#idofaelement").one("click", function(event) {
bitlyJSON(function(shortUrl) {
jQuery("#idofaelement").attr("href", function() {
//process shortUrl
//return finalized url;
});
setTimeout(function() {
window.location = jQuery("#idofaelement").attr("href");
}, 0);
});
return false;
});
Thanks for all the help!

Categories