Open external links in WordPress in an iFrame - php

I want to open all external links in an iframe like digg/themeforest.net
Most post on my site redirects users to external links and hence I want to use this method. I have searched a lot but couldn't find the answer I was looking for. Please help me get this done.
Thank you.
The solution I am looking for is
Question
When the link is clicked, if it is external it loads in iFrame

Supposing your iframe has id your-iframe
var $iframeSelector = $("#your-iframe");
var currentDomain = document.location.protocol + '//' + document.location.hostname;
var outboundLinks = 'a[href^="http"]:not([href*="' + currentDomain + '"])';
$(document).on('click', outboundLinks, function(){
$iframeSelector.attr('src', $(this).attr('href'))
});
Just add this to any javascript after DOM is loaded (in $(document).ready(function(){... }) block)

First you need to check if your anchor's href is external or internal, if it is external then load it in iframe
var comp = new RegExp( "your_site_url" );
var http_regez = new RegExp( "http" ); // for http:// and https://
var www_regez = new RegExp( "www" );
jQuery('a').click(function(event){
var href_val = jQuery(this).attr('href');
var is_external = false;
if(comp.test(href_val)){
is_external=false;
}
else if( http_regez.test(href_val) || www_regez.test(href_val) ){
is_external=true;
}
else{
is_external=false;
}
if(is_external){
event.preventDefault();
jQuery("#externalLinkIframe").attr('src',href_val);
return false;
}
});

Related

How to change html anchor tag query string

It is known that URL with querystring parameter can be rewritten with .htaccess. For example
localhost/mynews/category.php?cat=news&subcat=9
To
localhost/mynews/news/9
But is there any way to customize anchor tag
which is shown in bottom left corner while hovering link.
localhost/mynews/category.php?cat=news&subcat=9
to
localhost/mynews/news/9
PHP, jquery/javascript or htaccess, any way can we customize ?
On hover you can get your anchor href get querystring value rebuild url and set new url using attr in anchor tag.
var link = '';
$("a").hover(function() {
link = $(this).attr('href');
var var1 = $.urlParam('cat', link);
var var2 = $.urlParam('subcat', link);
var url = link.split('?')[0] + '/' + var1 + '/' + var2;
$(this).attr('href', url);
}, function() {
$(this).attr('href', link);
});
$.urlParam = function(name, link) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(link);
if (results == null) {
return null;
} else {
return decodeURI(results[1]) || 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hover Me
Note: I take urlParam function from https://stackoverflow.com/a/25359264/965146 and slightly modified it. Rest code are mine.You must reset your url when anchor click may be routing didn't get your new url

jQuery : AJAX Load Content No Page Refresh

I'm trying to load content without reloading the whole page with this code
$(document).ready(function() {
$('article').load('content/index.php');
$('a.cta , a').click(function() {
var page = $(this).attr('href');
$('article').load('content/' + page + '.php');
return false;
});
});
For the most part its working fine as seen here:
The only problem I'm getting is that the links withing my content area aren't working but every other link outside my content area is. Why is that? What am I missing in my code?
that is beacuse you need to delegate the dynamically added element with on. click events won't work for dynamically added elements..
try this
$(document).on('click','a.cta , a',function() {
var page = $(this).attr('href');
$('article').load('content/' + page + '.php');
return false;
});
});
delegating it to the closest static parent is recommended for better performance.
$(article).on('click','a.cta , a',function() {
link to read more about on delegated event
It's because those as within the article element are dynamic. The click event was never bound to those. Instead, use event delegation:
$('article').on('click', 'a.cta, a', function(e) {
e.preventDefault(); //better than return false
var page = $(this).attr('href');
$('article').load('content/' + page + '.php');
});
You have to use delegated events (on() function).
$('article').load('content/index.php', function () {
$("article").on("click", 'a.cta , a', function() {
var page = $(this).attr('href');
$('article').load('content/' + page + '.php');
return false;
});
});
See the documentation for more information.
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
I managed to get it to work with this :
$(document).ready(function() {
$('article').load('content/index.php', function () {
$(document).on('click','a.cta , a',function() {
var page = $(this).attr('href');
$('article').load('content/' + page + '.php');
return false;
});
});
});
It's really frustrating when you barely know what you are doing.
try commenting out the line return false; and all the links will work.
so...
return false;
change to...
//return false;

Change url with ajax call

I'm doing cross-domain GET to get cnn html like this:
$(function(){
var site = 'http://cnn.com';
$.get('proxy.php', { site:site }, function(data){
$(data).appendTo('#div');
}, 'html');
});
Im getting everything that I need except the url's sometimes are not complete urls but point to a certain path on there server like this:
/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3
So the problem is that if someone is clicking the link on my site the url will look like this:
http://MY-WEBSITE/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3
How can I get rid of my own url being inserted and replace it with 'cnn.com'?
I tried jquery split and replace but it doesn't work:
href = $(this).prop('href');
url = href.split('/');
href.replace(url[2], 'cnn.com');
I usually get an error in console 'split is not defined', when I fixed it the error moves on to 'url is not defined' and so on. Sometimes (with other code variations) I get no errors but it still doesn't work. I cant figure it out.
Looking at your code I am assuming you are using jQuery.
The problem is occurring because the source code on cnn.com seems to be using relative links. You can insert cnn.com at the beginning with the following jQuery
$(function() {
$('a').each(function() {
if ($(this).attr('href').indexOf('http') === 0) {
$(this).attr('href', 'http://www.cnn.com' + this.href);
}
});
});
You can simply check if the url is relative or not. Easiest way to do this is to check if it starts with http://.
var url = $(this).prop('href');
if (!(/^http/).test(url))
{
url = site + url; // prepend "http://cnn.com" to the address
}
alert(url); // url is now a full url
if you want a more generalised solution, you can use the regexp object on the site to determine if the prefix is there.
var site = "http://cnn.com";
var siteRegex = new RegExp("^" + site); // Regex - Starts with site
var url = $(this).prop('href');
if (!siteRegex.test(url))
{
url = site + url;
}
alert(url);
This little function can be used in a general purpose:
function RelativeToAbsoluteURL(root, url) {
var httpMatch = /https?:\/\//ig;
if (!httpMatch.test(url)) {
return root + (url.substr(0, 1) != "/" ? "/" + url : url);
} else {
return url;
}
}
Use:
RelativeToAbsoluteURL("http://www.cnn.com", "http://www.cnn.com/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3");
RelativeToAbsoluteURL("http://www.cnn.com", "/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3");
Both will output the same URL (http://www.cnn.com/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3)
DEMO
Either seems to work:
var href = $(this).attr('href');
var url = (href.indexOf("/")===0) ? "http://...."+href:href;
Possible alternative - this one will return the fully qualified URL from the href
var href = this.href; // actual href and not the property
var url =(href.indexOf(location.hostname)===7) ? href.replace(location.hostname,"www.cnn.com"):href;
Using prop
var href = $(this).prop('href');
var url = (href.indexOf("/")===0) ? "http://...."+href:href;

Pop-Up Window on page load

I need to have a pop-up window displayed when a page loads. What's happening is this. After an order is placed the user is redirected to their index page (main log-in page for the account) when they are redirected to the index page, I need a pop-up window to display on the page load that says something like "Your order for $variable has been saved". The $variable is defined on the previous page (where they are coming from) and I need that to carry over so I can display it in the pop-up box. Then once they click on "Ok" in the pop-up box, they are at the main page like always.
I have used a java popup box before on this project, but I am unsure of how to do one with these requirements. If there are any other/better ways to do this I am open to ideas. The layout of how this needs to work is below:
Client is logged into their account -> Order.php Page (Place an order) -> redirected to their member-index.php page (Pop-up needs to load on page load, and only when it comes from the order.php page)
Thanks!
Well from what I understand this would be the best match for you.
On previous page save a cookie (source http://www.quirksmode.org/js/cookies.html).
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
createookie("prevData", prevData, 30);
Then on the page you want the popup to appear (I suggest using an alert) (Note: you need the cookie code available on this page as well):
var prevData = readCookie("prevData");
if(prevData != null){
alert("Your order for " + prevData + " has been saved");
eraseCookie("prevData");
}
this could be in <body onLoad="code"> or simply a script in the header or anywhere really.
You can't force a popup page to open upon page load; browsers won't do that anymore. You can create a "fake" popup window by just positioning an element in the middle of the screen and decorating it so that it looks kind-of like a window. Various JavaScript libraries provide such "dialog" facilities.
`
function showpopup() {
var findString = /order.php/gi;
var referringURL = document.referrer;
var data = getQuerystring('variable');
if(referringURL.match(findString)) {
var windowprops = "left=50,top=50,width=500,height=500";
var preview = window.open("http://google.com", "preview", windowprops);
preview.document.write(data);
} else {
alert("Not order.php "+data);
}
}
function getQuerystring(key, default_) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
</script>
</head>
<body onload="showpopup()">
`
I assume you mean javascript. You may want to do this
<body onLoad="popup()">
Any code in the "onLoad" event should fire once the html is loaded.
If you are using Jquery, it should look like this
$("document").ready(function() {
popup();
});
You can pass your variable into the popup function.

jQuery: Click tracking with PHP

Yes, I KNOW about Google Analytics. We use it for our overall site metrics, and I know we can track individual links. However, we needed a tracking solution for very specific links and we need that tracking data available to our web application in real time, so I wrote my own solution:
jQuery:
$.fn.track = function () {
var source, url, name, ref, $this;
$this = $(this);
if (window.location.search.substring(1) != '') {
source = window.location.pathname + "?" + window.location.search.substring(1);
} else {
source = window.location.pathname;
}
url = jQuery.URLEncode($this.attr('href'));
name = $this.attr('name');
ref = jQuery.URLEncode(source);
$this.live('click', function (click) {
click.preventDefault();
$.post('/lib/track.php', {
url: url,
name: name,
ref: ref
}, function () { window.location = $this.attr('href'); });
});
};
... using the jQuery URLEncode plugin (http://www.digitalbart.com/jquery-and-urlencode/).
Now, this code works fine with my PHP backend and on my machine, but it doesn't seem to work reliably for everyone else. Sometimes the parameters passed in via jQuery are NOT passed in, resulting in a record in the database with no name, url or ref.
For the life of me, I can't figure out why this might be happening; I know the $.post is triggering, since there are records in the database (in the PHP, I also record the IP of the request along with the timestamp), but in many cases the PHP script is receiving blank $_POST variables from jQuery.
I've tested it live on every browser I have access to at my workplace, and all of them work fine for me; however, about 75% of all the records created (not by my computers) come through as blank (most of them are using the same browsers I am).
Why could this be happening?
I think, in the end, my problem ended up being that it was taking too long for the request to be parsed by jQuery, and I'm pretty adamant about not wanting to make the links "dependent" on javascript (either that they wouldn't work without it or that the user would have to wait for the tracking request to complete before they hit the new page).
After browsing many other solutions online--borrowing from some and being inspired by others--I arrived at the solution below in native javascript:
if (document.getElementsByClassName === undefined) { // get elements by class name, adjusted for IE's incompetence
document.getElementsByClassName = function(className) {
var hasClassName, allElements, results, element;
hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
allElements = document.getElementsByTagName("*");
results = [];
for (var i = 0; (element = allElements[i]) !== null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass)) {
results.push(element);
}
}
return results;
};
}
function addTracker(obj, type, fn) { // adds a tracker to the page, like $('xxx').event
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else if (obj.addEventListener) {
obj['e' + type + fn] = fn;
obj[type + fn] = function() {
obj['e' + type + fn]( window.event );
};
obj.attachEvent('on' + type, obj[type + fn]);
}
}
function save_click(passed_object) { // this function records a click
var now, then, path, encoded, to, from, name, img;
now = new Date();
path = '/lib/click.php';
from = (window.decode) ? window.decodeURI(document.URL) : document.URL;
to = (window.decodeURI) ? window.decodeURI(passed_object.href) : passed_object.href;
name = (passed_object.name && passed_object.name != '') ? passed_object.name : '[No Name]';
// timestamp the path!
path += '?timestamp=' + now.getTime();
path += '&to=' + escape(to) + '&from=' + escape(from) + '&name=' + name; // compile the path with the recorded information
img = new Image();
img.src = path; // when we call the image, we poll the php page; genius!
while (now.getTime() < then) {
now = new Date(); // resets the timer for subsequent clicks
}
}
function get_targeted_links(target) { // finds targeted elements and wires them up with an event handler
var links, link;
if (document.getElementsByClassName) {
links = document.getElementsByClassName(target);
for (var i = 0; i < links.length; i++) {
link = links[i];
if (link.href) {
addTracker(links[i], 'mousedown', save_click(links[i]));
}
}
}
}
addTracker(window, 'load', get_targeted_links('trackit'));
... which seems to be much snappier than the jQuery plugin I had written above, and so far has been fast enough to track all the requests I've thrown at it.
Hope that helps someone else!
These "clicks" might be coming from bots, or someone with JS disabled. If you the links clicked must be tracked why don't you consider JS only links, ie. put URL in a different attr other than href, then use your click handler to process it, add referral check in your track.php
Also have you checked if all elements are links?

Categories