Skip to main content

jQuery Inserting Script to Secure/Encrypted Pages

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

We ran into this time consuming problem and thought we would share it with people who encounter the same situation. Sorry about the length of this post, but it was a hell of a problem to fix!

Problem: Inserting a script into the DOM head tag dynamically when the page is being loaded using JavaScript/jQuery. This example see us trying to get an openX script to load on the page.

We encountered issues with:

  • IE8 causing Error Messages due to an encrypted page/website – To fix this we can do a check for an encrypted page and only load the OpenX script for pages that aren’t encrypted.
  • Loading a second script that references variables created by the first script leading to undefined error messages – To fix this we just added an if statement to check for the existence of the variable before using it.
  • document.write causing page to refresh – To fix do not use document.write after the page has been loaded.
(function() {

if (window.location.protocol !== 'https') {

	var openx = document.createElement('script'); openx.type = 'text/javascript'; openx.async = true;
    openx.src = '';
	
	//Insert into head
	var theHead = document.getElementsByTagName('head')[0];
	theHead.appendChild(openx); 
	
	console.log('script inserted into head');
}
})();

And if you want to include multi-line js script in the head (ie – not just a .js file) you can do it this way.

(function() {

	if (window.location.protocol !== 'https:') {

		/*Create dynamic scripts*/
		var openX = document.createElement('script'); 
		openX.type = 'text/javascript'; 
		openX.defer = 'defer'; /*defer is only supported by IE*/
		openX.async = true; /*async is a html5 proposal*/
		openX.src = '';
		var multiOpenX = document.createElement('script'); 
		multiOpenX.type = 'text/javascript'; 
		multiOpenX.defer = 'defer'; multiOpenX.async = true;
		multiOpenX.innerHTML = 
		   ['var OX_4ddf11d681ca9 = OX();',
			'OX_4ddf11d681ca9.addPage("2400");',
			'OX_4ddf11d681ca9.fetchAds();'
		   ].join('n');
		   
		/*Insert into head tag*/
		var theHead = document.getElementsByTagName('head')[0];
		theHead.appendChild(openX); 
		theHead.appendChild(multiOpenX); 
		
	}

})();

IE8 seems to produce errors when using the innerHTML tag in the head section. I cannot see a solution to this except from an alternative approach which doesn’t use innerHTML. We could revert to jQuery.getScript() and then pass in the second script parameters once the first has loaded like so:

$.getScript('ajax/test.js', function() {
    alert('Load was performed.');
});

Or even put it into a function and call it from the body like so:


	function LoadMyJs(scriptName) {
	var theHead = document.getElementsByTagName("head")[0];
	var dynamicScript = document.createElement("script");
	dynamicScript.type = "text/javascript";
	dynamicScript.src = scriptName;
	theHead.appendChild(newScript);
}

You can also write the multi-line script this way (warning: some browsers will insert newlines at the continuance, some will not).

var multiOpenX = 
' 
	var OX_4ddf23d681ca9 = OX(); 
	OX_4ddf231181ca9.addPage("2400"); 
	OX_4ddf231181ca9.fetchAds(); 
';

Final Script

Final script that worked in ALL browsers including IE8:

 
 
    if (window.location.protocol !== 'https:') { 
        /*load the OpenX script*/ 
          document.write(unescape('%3Cscript src="<path to script>" type="text/javascript"%3E%3C/script%3E')); 
    } 
</path> 
 
    if(typeof OX === 'function') 
    { 
       var OX_4ddf23d681119 = OX(); 
       OX_4ddf23d681119.addPage("2400"); 
       OX_4ddf23d681119.fetchAds(); 
    } 
 

Also check here for referncing different checks in the URL: http://www.jquery4u.com/javascript/javascript-location-hostnames-url-examples/

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn how Git works, and how to use it to streamline your workflow!


Google, Netflix and ILM are Python users. Maybe you should too?