Interstitial pages with javascript

When you click on a link, an interstitial page (usually an advert) appears before you are shown the new page that you clicked to view. doInterstitial() is a simple javascript function that rewrites all links on a page.


[source:javascript]

function doInterstitial(newURL, time) {
var links = document.getElementsByTagName(‘a’);
for( var i=0; i<links.length; i++) {
var oldURL = links[i].href;
links[i].href = newURL + ‘?oldURL=’ + oldURL + ‘&timer=’ + time;
}
}

[/source]

and can be called on page load (passing the advert url and a time duration for the advert):

[source:html]
<body onload=”doInterstitial(‘ad.html’, 2000);”>

[/source]

The following demonstrates a simple interstitial advert. Its basic function is to wait for a defined duration and then forward the user to their desired page.

The GET variables are parsed from the url, and used to find the duration and destination.

The biggest trick is the location.replace line which removes the advert from the history, stopping it appearing when the back button is pressed.

[source:html]

<html>
<head>
<title>Ad</title>
<script type=”text/javascript”>
function parseGetVars() {
var args = new Array();
var query = window.location.search.substring( 1 );
if( query ) {
var strList = query.split( ‘&’ );
for( str in strList ) {
var parts = strList[ str ].split( ‘=’ );
args[ unescape( parts[ 0 ] ) ] = unescape( parts[ 1 ] );
}
}
return args;
}
function addEvent(obj, evType, fn, useCapture){
if (obj.addEventListener){
obj.addEventListener(evType, fn, useCapture);
return true;
} else if (obj.attachEvent){
var r = obj.attachEvent(“on”+evType, fn);
return r;
} else {
alert(“Handler could not be attached”);
}
}
</script>
</head>
<body>
<script type=”text/javascript”>
var get = parseGetVars();
var oldURL = get['oldURL'];
var timer = get['timer'];
document.write(‘<p><a href=”#” onclick=”window.location=\”+oldURL+’\';return(false);”>Skip (will redirect to page in ‘+ parseInt(timer/1000) +’ seconds).</a></p>’);
addEvent(window, ‘load’, function() {
window.setTimeout(‘location.replace(\”+oldURL+’\')’, get['timer'])
}, false);
</script>
</body>
</html>

[/source]

Copyright @ BrandNewBox 2007

Tags: , ,

One Response to “Interstitial pages with javascript”

  1. rakim says:

    I still can;t get it to work. can you please post some demo somewhere? thx

Leave a Reply