How to use jQuery to access the DOM structure of parent HTML webpage from within the child HTML window

Sometimes, instead of showing a dialog box within a web page, it is more strategic to spawn a new HTML window as a dialog box to capture user input. This technique is especially useful when there are Java applets embedded in the web page, as Java applets tends to appear in front of every visual element on a HTML web page. There is no easy solution to place a visual element, for instance a HTML div, on top of Java applets.

Spawning another web page in another window is straightforward, but how do I send data collected from a child HTML window back to the parent HTML webpage? With this question in mind, I set out to find an answer.

A sample scenario

I will have a parent web page which contains a link for me to launch a child web page as a separate browser window. Within the child web page, I have a text field and a submit button for users to write messages back onto the parent web page.

The parent web page

Once I had created the sample scenario, I proceeded with building the parent web page.

With my HTML code reference and JavaScript code reference, I created the following HTML document:

<html>
<head>
	<title>How to use jQuery to access the DOM structure of parent HTML webpage from within the child HTML window</title>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
	<script type="text/javascript">
	
		$(document).ready(
			function () {
				$('#linkToSpawnChildWebPage').click(
					
					function (event) {
						event.preventDefault();
						window.open('http://www.techcoil.com/proof-of-concepts/adding-html-components-to-parent-web-page-dynamically-with-jquery','_blank','height=600,width=1024, status=yes,toolbar=no,menubar=no,location=no'); 
					}
				);
			}
		);
	
	</script>
</head>
<body>
	<a id="linkToSpawnChildWebPage" class="actionLink">Spawn child web page</a>
	
	<h3>Messages from child web page</h3>
	<div id="messagesArea">
	</div>
</body>
</html>

At the head section of the parent web page, I reference a jQuery library hosted by Google. By doing so, I attach a jQuery object to the web page's window object. In the JavaScript block that follows, I look for a HTML element with linkToSpawnChildWebPage as its id and attach a callback function for jQuery to notify my codes when the HTML element is being clicked. When that happens, the function is given an event object which I use for stopping linkToSpawnChildWebPage's default behaviour when it is being clicked on.

After calling event.preventDefault, I use the window object of the parent web page to launch the child web page in a window of its own.

In the body section of the parent web page, I show

  • a link element with id as linkToSpawnChildWebPage,
  • a header
  • and a div with messagesArea as its id to contain messages from the child web page

With the parent web page in place, I set out to build the child web page.

Getting a reference to the jQuery object in the parent web page from the child web page

In order for my child web page to access the DOM of the parent web page, I first write the JavaScript codes to get the window object of the parent web page.

var parentWindow = window.opener;

A call to window.opener from the child web page returns the window object of the parent web page that launches it. I define a variable, parentWindow, to give window.opener a easy-to-remember alias.

Sending the message from child web page to parent web page

With a variable that points to the window object of the parent web page, I proceed with writing the codes to send the message from the child web page to the parent web page:

function addMessageToWebPage(msg) {
    
    $messagesArea = parentWindow.$('#messagesArea');
    $messagesArea.html('<p>' + msg + '</p>' + $messagesArea.html());
	
}
		
$(document).ready(
	function() {				
		if (!parentWindow) {	
		    alert('Unable to get a reference to parent window.');		
		} 
		else {
			$('#messageForm').submit(				
				function(event) {
					addMessageToWebPage($('#messageTextField').val());
					event.preventDefault();
				}
							
			);
		}		
	}
);

I first define addMessageToWebPage which accepts a message from its caller. As the jQuery object is attached to the parent's window object, I call parentWindow.$ to query the DOM of the parent web page. I send a query to parentWindow.$ to look for the HTML element with messagesArea as its id, and remember it as $messagesArea. I then encapsulate the message from the caller with a HTML paragraph tag and append the result before the existing HTML content.

I then call $(document).ready and give it a function to prepare the child web page for interaction with the user. I first check whether parentWindow is successfully defined in the earlier JavaScript segment.

If it is not defined, it will mean that this web page is not open by another web page. I alert the user that the reference to the parent web page cannot be retrieved. If I have a reference to the window object of the parent web page, I attach a callback function to intercept form submission events from the HTML form with messageForm as its id.

In the given callback function, I call addMessageToWebPage, giving it the value found in the HTML text field with messageTextField as its id. I then stop the form submission with a call to event.preventDefault.

The child web page

For the view portion of the child web page, I reuse the same form from the proof of concept on using jQuery to add HTML components to a web page dynamically.

I add in the JavaScript codes mentioned earlier to the form and I get the following HTML document:

<html>
<head>
<title>Adding HTML components to parent web page dynamically with jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">

var parentWindow = window.opener;
	
function addMessageToWebPage(msg) {
    
    $messageArea = parentWindow.$('#messagesArea');
	$messageArea.html('<p>' + msg + '</p>' + $messageArea.html());
	
}
		
$(document).ready(
	function() {
						
		if (!parentWindow) {	
		    alert('Unable to get a reference to parent window.');		
		} 
		else {
			$('#messageForm').submit(				
				function(event) {
					addMessageToWebPage($('#messageTextField').val());
					event.preventDefault();
				}
							
			);
		}		
	}
);
						
</script>

</head>
<body>
	<form id="messageForm">
	<fieldset>
	    <label for="messageTextField">Message to add:</label>
	    <input id="messageTextField" name="messageTextField" type="text">
	</fieldset>
	<fieldset>
	        <input name="submitButton" type="submit" value="submit">
	</fieldset>
	</form>
</body>
</html>

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.