jQuery .click function converted to javascript - javascript

I wrote this script to pop up a confirm dialog when a user clicks on any link external from our site. It performs as expected on our internet site, however when I try to run this script on our FAQ portal, it does absolutely nothing. I believe it is blocking jQuery from running. What would be your recommendation to converting this script to javascript?
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function(){
$('a').click(function(){
if ((this.href.toLowerCase().indexOf("myfloridalicense.custhelp") > -1) ||
(this.href.toLowerCase().indexOf("myfloridalicense") > -1) ||
(this.href.toLowerCase().indexOf("javascript") > -1) ||
(this.href.toLowerCase().indexOf("dbprftp") > -1) ||
(this.href.toLowerCase().indexOf("interredesignalpha") > -1) ||
(this.href.toLowerCase().indexOf("bpr") > -1))
{
//Throw away
}
else {
if (window.confirm('NOTICE: By accessing this link, you will be leaving the DBPR website. DBPR is not responsible for the content of the Internet website you are entering. DBPR neither warrants nor makes any representations nor endorsements as to the accuracy, quality, content or completeness of the information, text, images, graphics, hyperlinks, and other items contained on the Internet website you are entering. DBPR is not responsible or liable for any viruses or contaminations of your hardware, software, peripherals or property, resulting from use of the Internet websites linked to or from the DBPR Internet website. Do you want to proceed?'))
{
// They clicked Yes
}
else
{
// They clicked no
return false;
}
}
});
});
</script>
Thanks in advance for your help!

My first guess would be that your portal has a listener attached for all anchor tags to prevent leaving the portal page. More than likely, jQuery is not blocked, the click on the anchor tag is blocked.
You can verify this by binding to the mouseup event on the anchor tags (or one in particular). It's possible that the portal is also cancelling those events, but many people only think to bind to the click.
If you have any control over the page, try adding a click listener to something OTHER than an anchor tag, say a specific div or list item. This will answer whether jQuery is active or not. Once you know the answer to that question, you can decide your next course of action.

function test(){
event.preventDefault();
var path = $('a').prop('href');
if ((path.toLowerCase().indexOf("myfloridalicense.custhelp") > -1) ||
(path.toLowerCase().indexOf("myfloridalicense") > -1) ||
(path.toLowerCase().indexOf("javascript") > -1) ||
(path.toLowerCase().indexOf("dbprftp") > -1) ||
(path.toLowerCase().indexOf("interredesignalpha") > -1) ||
(path.toLowerCase().indexOf("bpr") > -1))
{
//Throw away
}
else {
if (window.confirm('NOTICE: By accessing this link, you will be leaving the DBPR website. DBPR is not responsible for the content of the Internet website you are entering. DBPR neither warrants nor makes any representations nor endorsements as to the accuracy, quality, content or completeness of the information, text, images, graphics, hyperlinks, and other items contained on the Internet website you are entering. DBPR is not responsible or liable for any viruses or contaminations of your hardware, software, peripherals or property, resulting from use of the Internet websites linked to or from the DBPR Internet website. Do you want to proceed?'))
{
// They clicked Yes
}
else
{
// They clicked no
return false;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Link

Same as Keerthi's answer, but uses unobtrusive Javascript:
function test(){
if ((this.href.toLowerCase().indexOf("myfloridalicense.custhelp") > -1) ||
(this.href.toLowerCase().indexOf("myfloridalicense") > -1) ||
(this.href.toLowerCase().indexOf("javascript") > -1) ||
(this.href.toLowerCase().indexOf("dbprftp") > -1) ||
(this.href.toLowerCase().indexOf("interredesignalpha") > -1) ||
(this.href.toLowerCase().indexOf("bpr") > -1))
{
//Throw away
}
else {
if (window.confirm('NOTICE: By accessing this link, you will be leaving the DBPR website. DBPR is not responsible for the content of the Internet website you are entering. DBPR neither warrants nor makes any representations nor endorsements as to the accuracy, quality, content or completeness of the information, text, images, graphics, hyperlinks, and other items contained on the Internet website you are entering. DBPR is not responsible or liable for any viruses or contaminations of your hardware, software, peripherals or property, resulting from use of the Internet websites linked to or from the DBPR Internet website. Do you want to proceed?'))
{
// They clicked Yes
}
else
{
// They clicked no
return false;
}
}
}
document.getElementById('mySuperImportantLink').addEventListener('click', test, false);
HTML:
Link
See this SO question for more details on unobtrusive Javascript.

Related

Browser not detecting x-ua-compatible meta tag and setting to new IE browser version after changing it dynamically with javascript

We have a lot of old Infopath forms in an old Sharepoint 2010 website that runs in IE11. They want the site running in IE9 or above so we can run youtube videos. As far as everything other than Infopath forms, IE9-IE11 functions fine for our uses. The problem is that the Infopath forms will not open in any browser other than IE8. I believe it is something to do with the code triggered on the click of Infopath links being written for IE8, and not working in later versions.
I tried writing javascript that checks the page for any .xsn text (all of the links to Infopath files have .xsn in the link text), and if it finds it, it dynamically injects a tag into the to force IE8 Compatibility mode on. This obviously didn't work, as the browser had already read the meta info and ran in default IE11 mode. So, I tried an experiment using localStorage to see if it is at all possible to have javascript write in an x-ua-compatible meta tag before the browser chose its default version of IE11. Basically the code checks the page for .xsn text, and if it finds it, sets a localStorage property to true, then triggers a browser reload. Another piece of code checks localStorage for that property value, and if it is true, renders the x-ua-compatible meta tag into the . The code works as far as getting/setting the localStorage property correctly, and rendering the correct x-ua-compatible meta tag. I check the HTML after page load, and the meta tag is changing to IE compatibility mode on any page that has an Infopath form on it. However, it seems like the browser has already chosen it's version mode prior to that meta tag being written into the .
/**************************************************
script to insert meta tag to toggle
IE versions on the fly if Infopath forms
have been detected on the page
**************************************************/
if (localStorage.getItem('XSN-detect') !== null) {
//check localstorage for XSN-detect prop value
//if false, set meta tag to emulate IE11
if (localStorage.getItem('XSN-detect') === 'false') {
var link = document.createElement('meta');
link.setAttribute('http-equiv', 'x-ua-compatible');
link.content = 'IE=11';
document.getElementsByTagName('head')[0].appendChild(link);
}
//check localstorage for XSN-detect prop value
//if true, set meta tag to emulate IE8
if (localStorage.getItem('XSN-detect') === 'true') {
var link = document.createElement('meta');
link.setAttribute('http-equiv', 'x-ua-compatible');
link.content = 'IE=EmulateIE8';
document.getElementsByTagName('head')[0].appendChild(link);
//alert('This page contains Infopath forms, which requires IE8. Please press ok to have the page reload in IE8 mode.');
}
}
$(function() {
if (localStorage.getItem('XSN-detect') === null && document.getElementsByTagName('BODY')[0].innerHTML.indexOf('.xsn') != -1 || localStorage.getItem('XSN-detect') !== 'true' && document.getElementsByTagName('BODY')[0].innerHTML.indexOf('.xsn') != -1) {
localStorage.setItem('XSN-detect', 'true');
window.location.reload();
}
if (document.getElementsByTagName('BODY')[0].innerHTML.indexOf('.xsn') == -1) {
localStorage.setItem('XSN-detect', 'false');
}
});
I really just need to know if it is possible to dynamically change the x-ua-campatible meta tag and have the IE browser catch it before it chooses its version to load. I don't have access to update the C# or the config, so I am stuck with the front end.
My solution was to utilize the download.aspx?SourceUrl= and dynamically change all of the Infopath URLs on the page to use it. This causes all infopath files on Sharepoint 2010 (not including those with file:// urls) to download, rather than opening via Sharepoint's settings. Users then need to navigate to their downloads folder and open the file from there. The drawback is that users cannot open the form via any "open" commands in a browser. They have to open the file directly from where it downloaded. Considering the fact that Sharepoint2010 is so outdated, and most admins would prefer not to be stuck in IE8 modes any longer, I think it is an acceptable drawback.
$(function() {
if (document.getElementsByTagName('BODY')[0].innerHTML.indexOf('.xsn') != -1) {
$('a[href$=".xsn"]').each(function(index) {
var self = $(this);
var fileLocation = '';
var spDownloadsUrl = '/_layouts/download.aspx?SourceUrl=';
//GRAB LINK'S HREF LINK PATH AND URI ENCODE IT
var currentUrl = encodeURI(self.attr('href'));
//IF THE HREF IS TO A NETWORK FILE LOCATION EXIT THE PROCESS AND LEAVE IT ALONE
if (currentUrl.indexOf('file:') != -1) {
return;
}
//SHAREPOINT 2010 DOC LIST ELEMENTS HAVE INLINE JS ALTERING THE LINK BEHAVIOR, SO THEY NEED TO BE REMOVED
self.removeAttr('onclick');
self.removeAttr('onmousedown');
self.removeAttr('onfocus');
//IF THE LINK'S URL IS ABSOLUTE PATH, BUILD IT AS RELATIVE
if (currentUrl.indexOf('.com') != -1) {
var urlSplitOnDotCom = currentUrl.split('.com');
var urlAfterDotCom = urlSplitOnDotCom[1];
var urlPartsArr = urlAfterDotCom.split('/');
//REBUILD URL FROM ARRAY
var newPathname = "";
for (i = 1; i < urlPartsArr.length; i++) {
newPathname += "/";
newPathname += urlPartsArr[i];
}
fileLocation = newPathname;
} else {
fileLocation = currentUrl;
}
//ADD NEW URL TO INFOPATH FILE'S HREF ATTRIBUTE
self.attr('href', spDownloadsUrl + fileLocation);
});
}
});

Some links ignoring EventListener

Update
User Quentin helped me solve it. The lightbox had a event.stopPropagation(); in the function which prevented the eventlistener from bubbling up. After removing it the links worked properly.
I used this comment with honyovk's addition to replace the stopPropagation with a more elegant function: https://stackoverflow.com/a/1089622/3461722
Question
I have a webapp for iOS in which I use an EventListener to prevent links from opening in Safari. This works flawless for 99% of the links, but a few specific links still open in Safari for some reason unknown to me.
This is my Javascript:
// Mobile Safari in standalone mode
if(("standalone" in window.navigator) && window.navigator.standalone){
// If you want to prevent remote links in standalone web apps opening Mobile Safari, change 'remotes' to true
var noddy, remotes = false;
document.addEventListener('click', function(event) {
noddy = event.target;
// Bubble up until we hit link or top HTML element. Warning: BODY element is not compulsory so better to stop on HTML
while(noddy.nodeName !== "A" && noddy.nodeName !== "HTML") {
noddy = noddy.parentNode;
}
if('href' in noddy && noddy.href.indexOf('http') !== -1 && (noddy.href.indexOf(document.location.host) !== -1 || remotes))
{
event.preventDefault();
document.location.href = noddy.href;
}
},false);
}
The links that fail to open in the webapp are nothing special, and other links on the page work without problem. An example of a not properly working link:
Buy
This link is opened in a lightbox, but on other pages I have similar links also in a lightbox and they work fine. I have several popups with roughly the same link, only the "green" is different and some have an extra "&time=1", they all fail to open in the webapp.
Is there someone who can find fault with this code?

How to catch Javascript:void(0)

I wrote this script to pop-up a message any time a user clicks on an external link from our site. When I wrote this I assumed the best way to do this would be to check location.host and compare it to the url the user is attempting to visit.
<script type="text/javascript">
$(function(){
$('a').click(function(){
if (this.href.match(location.host)) {
//alert('Please continue on to our site.');
window.onbeforeunload = null;
}
else {
if (window.confirm('NOTICE: By accessing this link, you will be leaving the DBPR website. DBPR is not responsible for the content of the Internet website you are entering. DBPR neither warrants nor makes any representations nor endorsements as to the accuracy, quality, content or completeness of the information, text, images, graphics, hyperlinks, and other items contained on the Internet website you are entering. DBPR is not responsible or liable for any viruses or contaminations of your hardware, software, peripherals or property, resulting from use of the Internet websites linked to or from the DBPR Internet website. Do you want to proceed?')
){
// They clicked Yes
}
else
{
// They clicked no
return false;
}
}
});
});
</script>
The way the code currently stands, it works in the majority of cases, however I noticed that a couple buttons on our home page reference javascript:void(0), and they cause the confirm box to prompt on click .
Is there a way you would recommend to treat javascript:void(0) as an internal link or completely diregard it?
Thanks,
TG
You could do it like this:
if (this.href.match(location.host) ||
this.href.toLowerCase().indexOf('javascript') !== -1) {
// allow
}

How to programmatically add list of web-pages to browser favourites on click?

I currently have a list of useful webpages that I am adding to my web-page. I would like to add a link next to each URL that will add it as a bookmark in the users browser. How can I do this?
Further to this, how can I add a "Bookmark all links" button to my page ?
Bookmarking for the user isn't supported by some major browsers. You might want to just let the users do it themselves. If you insist, however, this post has some code Bookmark on click using jQuery
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$("a.jQueryBookmark").click(function(e){
e.preventDefault(); // this will prevent the anchor tag from going the user off to the link
var bookmarkUrl = this.href;
var bookmarkTitle = this.title;
if (window.sidebar) { // For Mozilla Firefox Bookmark
window.sidebar.addPanel(bookmarkTitle, bookmarkUrl,"");
} else if(( window.external && window.external.AddFavorite) || document.all) { // For IE Favorite
window.external.AddFavorite( bookmarkUrl, bookmarkTitle);
} else if(window.opera) { // For Opera Browsers
$("a.jQueryBookmark").attr("href",bookmarkUrl);
$("a.jQueryBookmark").attr("title",bookmarkTitle);
$("a.jQueryBookmark").attr("rel","sidebar");
} else { // for other browsers which does not support
alert('Your browser does not support this bookmark action');
return false;
}
});
});
</script>
This Code is taken from Developersnippets!
Chrome does not support such actions, since the security level could be broken.

Some browsers (IE8 and possibly others) not interpreting these javascript conditions correctly to determine an outbound link

I'm trying to isolate outbound links automatically with jQuery so that I can track them with Google Analytics. The following works in Chrome, but in IE8 and possibly some other browsers, links with href="#1" are being tracked as outbound links.
$('a').each(function () {
if (this.href.length >= 3 && this.href.indexOf('http') >= 0 && this["hostname"].replace('www.','') != window.location.hostname.replace('www.','')) {
// Do stuff
}
});
I'm guessing maybe IE8 adds the current url to the start of a # link, which would let it past the second condition, but the third condition should still stop it shouldn't it?
Does anyone know how I can stop this from happening?
If you want to see the literal text of the href attribute, rather than how it's canonicalized by the browser, use:
$(this).attr('href')
rather than
this.href

Categories