I am using a script i found here to dynamically generate short link for my Tweet buttons and it works perfectly well, but the only thing i cant seem to do is create the link to open in either a new tab or preferably a popup window.
I have tried several variations of the window.location section of the script but so far I've had no luck. If anybody could point me in the right direct I'd be very grateful.
This is the script I am using...
<script>
var TweetThisLink = {
shorten: function(e) {
// this stops the click, which will later be handled in the response method
e.preventDefault();
// find the link starting at the second 'http://'
var url = this.href.substr(this.href.indexOf('http:', 5));
BitlyClient.shorten(url, 'TweetThisLink.response');
},
response: function(data) {
var bitly_link = null;
for (var r in data.results) {
bitly_link = data.results[r]['shortUrl'];
break;
}
var tweet_text = "Text for the Tweet goes here"
window.location = "http://twitter.com/home?status=" + encodeURIComponent(tweet_text + ' ' + bitly_link + " #Hashtag1 #Hashtag2");
}
}
jQuery('.tweetlink').bind('click', TweetThisLink.shorten);
</script>
Many thanks in advance :)
Normally you could just do window.open:
window.open("http://twitter.com/home?status=" + encodeURIComponent(tweet_text + ' ' + bitly_link + " #Hashtag1 #Hashtag2");
BUT, since you are doing an ajax call before this happens, chances are that this window popup will be blocked by the browser, since the window.open command is no longer associated with the click (browsers allow a certain time before a window.open command falls under non-initiated "popup").
A solution would be to first open the window on click (in your shorten function):
var win = window.open('about:blank');
And then redirect in your response function:
win.location = 'http://twitter.com/etc...';
Demo: http://jsbin.com/usovik/1
Perhaps you're looking for
window.open("http://example.com");
Related
Section on my website with a list of fixtures.
When I click on one it loads the fixture information in a modal window - each club might have an image so I want to check if there is an image and if so display it otherwise display a generic image.
Code is below:
$('#fixModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var hclub = button.data('hclubid')
imgpath = "/images/clubcrests/"
homecrest = imgpath + hclub + '.jpg'
gencrest = imgpath + 'generic.jpg'
$.get(homecrest)
.done(function() {
homecrestsrc = "<img src='" + homecrest + "'>"
}).fail(function() {
homecrestsrc = "<img src='" + gencrest + "'>"
})
var modal = $(this)
modal.find('.fixmodhomec').html(homecrestsrc)
})
But first time I click on it I get the error:
homecrestsrc is not defined
$.get seems to run after the modal.find.
If I click on it again it displays but always the image it should have from the previous time the button was clicked.
How can I make sure the $.get bit runs first?
$.get is asynchronous - did you read the documentation? modal.find will have run long before the response from the AJAX call has come back.
You need to move your logic inside the callbacks.
$('#fixModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget),
hclub = button.data('hclubid'),
modal = $(this),
imgpath = "/images/clubcrests/",
homecrest = imgpath + hclub + '.jpg',
gencrest = imgpath + 'generic.jpg',
homecrestsrc;
$.get(homecrest).done(function () {
homecrestsrc = "<img src='" + homecrest + "'>"
}).fail(function () {
homecrestsrc = "<img src='" + gencrest + "'>"
}).always(function () {
modal.find('.fixmodhomec').html(homecrestsrc);
});
})
This is the confusing part of js/ajax. This code does not wait for an ajax reaponse, but instead jumps strait on to the next command. Meaning it will continue with your last 2 lines of code, and then the response will come thru, and then it will set homecrestsrc for the first time. Whatever you expect to be done AFTER you get a reaponse, you put in done and fail. So put your last or last 2 lines of code inside the done and fail functions.
Sry typing from phone so i cant explain too much, but hope you understand, it takes time to get it bcs this is not so obvious when you start
The other answer kind of covered this... basically, if the code below the get request depends on that result, it needs to be inside the .done() block.
However, I'd also like to point out that having your image displaying depend on the whether a get request fails or not is bad practice. You should instead have your api route return true if that image exists or false if it doesn't. Then you can filter the correct picture in a .success() block.
.fail() should be reserved for debugging only.
I am trying to reload a parent window (same domain) with javascript from within an iframe.
window.parent.location.href = window.parent.location.href;
does not work here for some reason (no javascript errors).
I don't believe it is a problem with same origin policy, as the following works:
window.parent.location.reload();
The problem with this option is if the last request was a POST, it gets reloaded as POST.
Any ideas why the first option wouldn't work? Otherwise, is there another method that will reload the page without resubmitting any form data (e.g. perform a fresh GET request to the parent page URL)?
I have also tried:
top.frames.location.href = top.frames.location.href;
window.opener.location.href = window.opener.location.href
and various other iterations.
I tried this code:
window.location.href = window.location.href;
in an ordinary page (no frames) and it had no effect either. The browser must detect that it is the same URL being displayed and conclude that no action needs to be taken.
What you can do is add a dummy GET parameter and change it to force the browser to reload. The first load might look like this (with POST data included, not shown here of course):
http://www.example.com/page.html?a=1&b=2&dummy=32843493294348
Then to reload:
var dummy = Math.floor(Math.random() * 100000000000000);
window.parent.location.href = window.parent.location.href.replace(/dummy=[0-9]+/, "dummy=" + dummy);
Phari's answer worked for me, with a few adjustments to fit my use case:
var rdm = Math.floor(Math.random() * 100000000000000);
var url = window.parent.location.href;
if (url.indexOf("rdm") > 0) {
window.parent.location.href = url.replace(/rdm=[0-9]+/, "rdm=" + rdm);
} else {
var hsh = "";
if (url.indexOf("#") > 0) {
hash = "#" + url.split('#')[1];
url = url.split('#')[0];
}
if (url.indexOf("?") > 0) {
url = url + "&rdm=" + rdm + hsh;
} else {
url = url + "?rdm=" + rdm + hsh;
}
window.parent.location.href = url;
}
I'm sure this could be more efficient, but works ok.
Is there a way to detect if tab shows 'error page'?
I mean, for example, if user enters any http://non-existing-url.com or just site is unavailable.
Anything similar to Chrome's webNavigation.onErrorOccured event.
If there is no similar event, perhaps there is a way to check Tab http status (200, 404, 502, 0, etc...)?
Whoops didn't see this topic. Here is how you can do it look for about:neterror load
from: mozillaZine :: Detecting “problem loading page” in firefox
have to read the docuri through the webNavigation of the browser. because the window.location is different
anyways the docuri is real nice when an error it happens. it clearly tells you whats wrong with it in the e parameter.
theese are examples of some docuris that load:
about:neterror?e=dnsNotFound&u=http%3A//www.cu.reporterror%28%27afew/&c=UTF-8&d=Firefox%20can%27t%20find%20the%20server%20at%20www.cu.reporterror%28%27afew.
about:neterror?e=malformedURI&u=about%3Abalk&c=&d=The%20URL%20is%20not%20valid%20and%20cannot%
you can see the first one is dnsNotFound and the second one is malformedURI
var listenToPageLoad_IfProblemLoadingPage = function(event) {
var win = event.originalTarget.defaultView;
var webnav = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation);
//console.log('webnav:', webnav, 'webnav of selectedtab:', window.gBrowser.webNavigation);
var docuri = webnav.document.documentURI; //can also try event.originalTarget.linkedBrowser.webNavigation.document.documentURI <<i didnt test this linkedBrowser theory but its gotta be something like that
var location = win.location + ''; //I add a " + ''" at the end so it makes it a string so we can use string functions like location.indexOf etc
if (win.frameElement) {
// Frame within a tab was loaded. win should be the top window of
// the frameset. If you don't want do anything when frames/iframes
// are loaded in this web page, uncomment the following line:
// return;
// Find the root document:
//win = win.top;
if (docuri.indexOf('about:neterror') == 0) {
Components.utils.reportError('IN FRAME - PROBLEM LOADING PAGE LOADED docuri = "' + docuri + '"');
}
} else {
if (docuri.indexOf('about:neterror') == 0) {
Components.utils.reportError('IN TAB - PROBLEM LOADING PAGE LOADED docuri = "' + docuri + '"');
}
}
}
window.gBrowser.addEventListener('DOMContentLoaded', listenToPageLoad_IfProblemLoadingPage, false);
I have the following code within an external javascript file.
jQuery(function ($) {
//////////////////////UPCOMING EVENTS JSON SERVER START///////////////////////////
var eventList = $("#eventList"); //cache the element
$.getJSON("/JsonControl/Events.json", function (jsonObj) {
val = "";
for (var i = 0; i < jsonObj.events.length; ++i) {
val += "<p>" + jsonObj.events[i].dateMonth + "/" + jsonObj.events[i].dateNumber +
"/" + jsonObj.events[i].dateYear + " - <span id='EL" + i + "' class='link' " +
"onclick=plotEvent(" + i +")>" + jsonObj.events[i].title + "</span></p>";
}
eventList.html(val);
});
//////////////////////UPCOMING EVENTS JSON SERVER END/////////////////////////////
});
function plotEvent(index)
{
$.ajax({
url: "/JsonControl/Events.json",
dataType: 'json',
async: false,
success: function (jsonObj)
{
var eventBox = window.frameElement;
alert("This alert fires in all browsers, including IE9")
eventBox.onload = function ()
{
alert("This alert doesn't fire in IE9.")
window.frameElement.onload = null; // unset it so it only fires once
eventBox = eventBox.contentDocument || eventBox.contentWindow.document;
eventBox.getElementById("title").innerHTML = (jsonObj.events[index].title);
eventBox.getElementById("content").innerHTML = (jsonObj.events[index].explanation);
eventBox.getElementById("dateHolder").innerHTML = (jsonObj.events[index].dateMonth + "-" + jsonObj.events[index].dateNumber + "-" + jsonObj.events[index].dateYear);
};
eventBox.src="/Event htms/Event.htm";
}
});
}
The page that loads this script is in the iframe itself. A very similar function called in a different external js file, from the main page outside of the iframe (for a different but similar purpose) works in all browsers just fine. The only difference is that with this code I have to target the onload of the iframe from within the iframe, instead of just grabbing the iframe by id. I then attempt to change, the onload of said iframe, for use with the next internal iframe page (which is why I need to preserve the json array index [i] when dynamically writing the first iframe page's innerHTML.
Sorry if that was a bit wordy, and/or confusing, but suffice it to say that with using the above-pasted code, I have no problems... except with IE (tried in IE9). I have tried dozens of examples and supposed solutions, but nothing has worked. Using IE9.
Here's what I mean when I say 'it doesn't work in IE9':
This part of the code within plotEvent() doesn't fire:
eventBox.onload = function ()
{
alert("This alert doesn't fire in IE9.")
window.frameElement.onload = null; // unset it so it only fires once
eventBox = eventBox.contentDocument || eventBox.contentWindow.document;
eventBox.getElementById("title").innerHTML = (jsonObj.events[index].title);
eventBox.getElementById("content").innerHTML = (jsonObj.events[index].explanation);
eventBox.getElementById("dateHolder").innerHTML = (jsonObj.events[index].dateMonth + "-" + jsonObj.events[index].dateNumber + "-" + jsonObj.events[index].dateYear);
};
Is there any solution to this problem, or is this sort of thing why iframes aren't used more often (that is, that IE doesn't fully support them)?
Try eventBox.contentWindow.onload or maybe $(eventBox).load(function)
I'm trying to launch a popup from certain pages. I want users to see the popup only when:
a) they close the browser tab
b) they hit the browser's Back button
c) they go to a page other than the next step in the purchase path - basically, when they go to any URL that does not contain the string "/checkout/".
I've looked at popup examples that load body onUnload, and that's a bit too global. I just want a popup - a true actual popup - to launch if they try to leave the checkout path.
I've looked at several questions on StackOverflow, but none of them quite seem to answer my question. The onBeforeUnload mentioned in this answer https://stackoverflow.com/a/3753963/1634459 might work...MIGHT...but I'm not totally sure how to implement it with the conditions I listed above.
...help?
Here's the popup window code I'd like to use:
<script language="javascript" type="text/javascript">
var win=null;
function NewWindow(mypage,myname,w,h,scroll,pos){
if(pos=="center"){LeftPosition=(screen.availWidth)?(screen.availWidth-w)/2:50;TopPosition=(screen.availHeight)?(screen.availHeight-h)/2:50;}
settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
win=window.open(mypage,myname,settings);
if(win.focus){win.focus();}}
function CloseNewWin(){if(win!=null && win.open)win.close()}
window.onfocus=CloseNewWin;
</script>
Here you go; I wrote this for the marketing team at a previous job. You should be able to adapt it pretty easily; just update the URL and params as appropriate.
This code will open a popup when the user leaves the page, unless they leave by submitting the checkout form. (If you have more than one form on the page, which you shouldn't in a checkout flow, you will need to fix that as well.)
var nag = function () {
return {
// assume the user is going to leave, get ready to pounce!
doWant: true,
// FALCON PUNCH
deploy: function () {
if (nag.doWant) {
var width = 449;
var height = 298;
args = "width=" + width + ",";
args += "height=" + height + ",";
args += "location=0" + ","
args += "menubar=0" + ","
args += "resizable=1" + ","
args += "scrollbars=0" + ","
args += "status=0" + ","
args += "titlebar=0" + ","
args += "toolbar=0" + ","
args += "hotkeys=0"
var demo_window = window.open("YOUR_URL", "main", args);
try {
demo_window.focus();
} catch (err3) { };
}
},
// oh, off to step 2? that's cool. carry on.
ignore: function () {
nag.doWant = false;
}
}
} ();
window.onunload = nag.deploy;
document.forms[0].onsubmit = nag.ignore;
If you want to be able to STOP the user from leaving the page, I can help you with that update.