Recently asked on Yahoo! Answers:
I’m trying to figure out a way to use javascript to load a random link every 10 seconds in a new window.
For example, let’s say that I want to load a different Yahoo! Search page every 10 seconds with a different search term.
In the following URL, the ‘SEARCHTERM’ part should be replaced with a random word defined in the javascript: http://search.yahoo.com/search?p=searcht…
I’m not too familar with Javascript which is the reason to why I’m trying to learn. I think that making a list of words should be in the following format from what I’ve seen in other scripts, but I’m not sure:
[0]word1
[1]hello+world
[2]laptop+computers
[3]all+your+base+are+belong+to…
—-Is anyone out there who can help me develop this script? Hopefully someone who knows javascript inside and out and whip together a little example for me in no time at all so that I can continue learning and actually building something from what I learn.
Thanks in advance!
Without fail, the projects that seem like they’re a snap turn into the projects that never, ever end, and that was certainly the case with this request. It took me quite a while to overcome the various obstacles presented by this question and I had to make a couple compromises to get it to work consistently in both Internet Explorer and Firefox.
But without further ado, I’m proud to present the product of about six hours of toil over a hot monitor: A primarily JavaScript, plus a little PHP, solution to pop up random Yahoo! Web searches in a productive manner.
My intial thought on this was that it would be relatively simple:
- Create an array of all the search terms you want to load
- Dynamically create a URL for search.yahoo.com to search for those terms
- Open a window and feed the URL to it
- Refresh the script every 10 seconds
However, after doing just that, some problems immediately arose.
- I needed to know the state of the pop-up window (whether it was open or not); feeding the URL to a closed window, or constantly trying to open an already opened window, causes all kinds of JavaScript errors.
- The 10-second refresh of the page goes too fast; you can’t examine the search results fast enough to work with them before they’re refreshed.
- And the worst issue: If you clicked a link in the search results of the pop-up window, within 10 seconds, that window would refresh, again, with new search results. There had to be a way to work with the results so it didn’t get refreshed.
The Main Page JavaScript
Let’s first examine the JavaScript that will load the popup window and feed it the search terms we want. For reasons that I’ll explain later, we’re going to actually pop up a frameset.
We begin by declaring some global variables and creating a function that we’ll invoke on page load: one function will give us the dimensions we should use for the popup window, based on the size of the user’s screen, and the other will invoke our popup.
var windowRef; var scriptInterval = 30000; var winW, winH; function pageLoad() { setWindowSize(); randomSearch(); }
The setWindowSize function first sets some default, or minimum, sizes for the popup window; it then determines the Web browser (user agent) of the visitor, so that we can use the proper JavaScript window properties to get the size of the current browser window.
Based on what browser is being used, we get the dimensions of the current page, then set the size of our popup window to be 80 percent of that size. If either the width or the height of the window will be smaller than the minimum sizes, we set that dimension to be the minimum size.
We store the window dimensions as global variables because it will save us many headaches in trying to pass the variable to the popup window script; because the popup window script is on a timer, passing variables to it will be problematic, so globals spare us the trouble of working through that.
function setWindowSize() { var minW = 600; var minH = 400; var agt = navigator.userAgent.toLowerCase(); var is_ie = ((agt.indexOf('msie') != -1) && (agt.indexOf('opera') == -1)); if(!is_ie) { winW = window.innerWidth; winH = window.innerHeight; } else { winW = document.body.offsetWidth; winH = document.body.offsetHeight; } winW = Math.floor(winW * 0.8); winH = Math.floor(winH * 0.8); if(winW < minW) { winW = minW; } if(winH < minH) { winH = minH; } }
The next thing we do is create the JavaScript function, randomSearch(), that will actually do the popping up of windows.
That function first declares an array of all the search terms we want to use. We then generate a random number and multiply it by the array’s length (number of items). We round that number off to the integer portion of that random number; the result will be the index of the array that we will feed as the search term to the popup window.
We next dynamically construct the URL of the search window, as well as the attributes we want for the popup window (scrollbars, toolbars, etc.).
We check whether the popup window has been invoked yet, by seeing if it is undefined. If it’s undefined, we know this is the first time the script is executing, so we assign an object the value of window.open; that defines the variable.
We need to define this variable because of subsequent calls to this script. As noted previously, if you try to call window.open on an already open window, that will create an error. If we try to change the location of a window that isn’t open, that, too, will create errors. So, we use the windowRef variable to hold the state of the popup window; it will track for us whether the window is open or not, so we can properly handle sending it a new URL or reopening it.
Finally, we assign a timer variable the name of this fuction and the interval, in milliseconds, at which we want this function recalled by the page; 30,000 equals 30 seconds. Again, I’m using 30 seconds here because in early testing, I determined 10 seconds just wasn’t long enough.
function randomSearch() { var searchArray = new Array( 'puppies', 'shoe shine supplies', 'Paris Hilton', 'nuclear bomb plans', 'ugly people', 'javascript', 'pig Latin', 'bad odors', 'Abraham Lincoln' ); var itemCount = searchArray.length; var searchIndex = Math.random(); searchIndex *= itemCount; searchIndex = Math.floor(searchIndex); if(searchIndex == searchArray.length) { searchIndex--; } var popupUrl = 'popup.html?' + escape(searchArray[searchIndex]); var popupOpts = 'width=' + winW + ',height=' + winH + ',status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1,scrollbars=1' if(windowRef == undefined) { windowRef = window.open(popupUrl, 'popupWindow', popupOpts); } else { if(windowRef.closed) { windowRef = window.open(popupUrl, 'popupWindow', popupOpts); } else { windowRef.location = popupUrl; } } timerId = setTimeout('randomSearch()', scriptInterval); }
Finally, this page needs a way to start and stop the popup window, at least for the purposes of testing, if not to keep people from leaving the site because the popup window keeps coming back, even after they’ve closed it. We do that by either using clearTimeout() to stop the popups, or calling randomSearch() to start it again.
As a neat trick, we’ll dynamically change the link to show the status of the popup window system: started or stopped.
function timerToggle(status) { var toggleDiv = document.getElementById('timerControl'); if(status == 'on') { randomSearch(); toggleDiv.innerHTML = '<p><a href="#" onclick="timerToggle('off')">Stop popup window</a></p>'; } else { clearTimeout(timerId); toggleDiv.innerHTML = '<p><a href="#" onclick="timerToggle('on')">Start popup window</a></p>'; } }
The HTML segment of the page that controls the timerToggle() function is this div:
<div id="timerControl"><p><a href="#" onclick="timerToggle('off')">Stop popup window</a></p></div>
The Popup Window
The popup window itself is a simple HTML frameset in two rows; the top frame has a height of 40 pixels, the bottom frame takes up whatever space is left.
The top frame will hold the JavaScript functions that will make our search actually work. It accepts, from the frameset (the “parent” page), the querystring (search terms) our main page function sent to the popup window. It then creates a URL to call a PHP page, concatenating on the search terms we want to use. Finally, the bottom frame’s location is set to be that URL.
Why do we go through all this trouble? Because again, the problem we have is that every 30 seconds, this search is going to be reloaded. We need a way to tell users that.
But even worse, the main page is going to refresh this popup every 30 seconds. So, if we click on one of the search links currently being displayed to go to a new page, very shortly, that page will be replaced by a new search term results page — making this entire exercise pretty useless.
Somehow, we need to be able to stop the popup window from being refreshed if the user has clicked on one of the search links we’ve already shown, or, at the very least, get the search terms links to appear in a new window. More on that shortly. The basic point is, it’s easiest to control content we have on our site, versus content someplace else.
Here’s the code for the topframe.html page load:
var timeLeft; function loadThePage() { var frameUrl = 'bottomframe.php?p='; var qstring = parent.location.search; if (qstring.substring(0, 1) == '?') { qstring = qstring.substring(1); } frameUrl += qstring; parent.bottomFrame.location = frameUrl; timeLeft = 30000; updateStatus(); }
Notice the last two lines. We’re going to have another function, called updateStatus, which will show, in a div of this frame, the time remaining until refresh — so that the refresh doesn’t come as a shock to our users.
function updateStatus() { var seconds = timeLeft / 1000; var out = 'The search page below will change in ' + seconds + ' seconds.'; var thediv = document.getElementById('statusMessage'); thediv.innerHTML = out; timeLeft -= 1000; setTimeout('updateStatus()', 1000); }
The bottomframe.php Page
Again, the problem we have is that we can certainly make requests to search.yahoo.com and display those results in a new Web browser window, but because we’re doing that on a timer, we’ve got to find a way to stop the timer if someone clicks on one of those search results links — or, at the very least, make that refresh a non-issue.
After playing with all sorts of JavaScript and finding it didn’t go well, I came to a simple solution: Why not just add a base tag to the Yahoo! search results page?
In HTML, base allows you to specify a target page for all the links on the page. And fortunately, Yahoo! search pages don’t contain the base tag, and the head tag is clean; it has no attributes. That makes finding the head tag, and replacing it with extra tags, a snap.
Rather than displaying the Yahoo! search page itself in the lower frame, we’ll use PHP to get the search page results, reprocess the HTML, add a base target="_blank" tag to the search results page, and echo the entire page out to the lower frame. Then, whenever someone clicks on a link in the search results, it will open in a blank window.
We can fetch a Web page via curl or fopen in PHP. Many hosts (mine included) don’t allow you to provide a URL as an argument for fopen, because that has security implications; the ones that don’t tend to have curl, a library of that allows you to access Internet services of all sorts.
$url = "http://search.yahoo.com/search?p=" . urlencode($_GET['p']); $pagetext = ""; /* START curl codeblock START */ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $pagetext = curl_ exe c($ch); //remove spaces in curl_exec curl_close($ch); $pagetext = str_replace("<head>", "<head>n<base target="_blank">n", $pagetext); echo $pagetext;
The page appears to be the same as the search page you’d get from going direct. And believe it or not, that’s it.
You can view this solution in action here: http://www.dougv.com/demo/randomsearch/ Warning: This entire script operates on pop-ups, so if you are using a pop-up blocker, you’ll need to disable it.
You can also download the source code here:
Displaying A Random Yahoo! Search Every 30 Seconds With JavaScript And PHP
As always, I distribute code under the GNU GPL version 3.

Wow, that’s great! Thanks for answering my question on Yahoo! Answers. I really owe you a lot for this! You should now submit this link to other sites to get yourself some more traffic to this blog. You seem like a cool dude!