Previous Page
Next Page

Keeping a Page out of a Frame

Other people can put one of your pages inside a frame on their site, making it appear that your page is part of their content. In JavaScript, windows appear in a hierarchy, with the parent window at the top of the heap. When someone hijacks your page, they are forcing it to be a child frame to their parent window. Figure 5.2 shows how the page would appear as part of someone else's site. With these scripts, you can prevent this page hijacking and force your page to always be in a browser window by itself. There are two scripts; Script 5.1 is the HTML page that should always stand alone and has the <script> tag that calls the JavaScript; Script 5.2 is the JavaScript document, which we'll describe next.

Figure 5.2. Our page, buried in someone else's frameset.


Script 5.1. Here is an HTML page that people want to hijack.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>Can't be in a frame</title>
     <script language="javascript" type="text/javascript" src="script01.js"></script>
</head>
<body bgcolor="#FFFFFF">
     <h1>A really important page here that everyone wants to claim as theirs.</h1>
</body>
</html>

Script 5.2. JavaScript provides a way to force our page to always appear on a separate page.

if (top.location != self.location) {
     top.location.replace(self.location);
}

To isolate a page:

1.
if (top.location != self.location) {



First, check to see if the location of the current page (self) is the top-most in the browser window hierarchy. If it is, there's no need to do anything.

2.
top.location.replace(self.location);



If the current page isn't at the top, replace the top page with the location of the current page. This forces the current window to be our page and our page only. Figure 5.3 shows our page as we designed it.

Figure 5.3. Our page, after escaping from the evil hijacking frameset.


Tip

  • We could just set top.location to self.location, but this has one nasty side effect: users can no longer use the browser's back button. If they try to, going back to the previous page automatically jumps them back to the current page. Using the replace() method shown above replaces the current page in the history, which allows the back button to display the previous page.



Previous Page
Next Page