Discussions

Web tier: servlets, JSP, Web frameworks: Servlet - Javascript Pop-up

  1. Servlet - Javascript Pop-up (2 messages)

    I am wanting to create a pop-up window from a servlet generated page when an image is clicked within the page. The pop-up window needs to be able to display a string variable that is passed to it from the servlet page.

    Threaded Messages (2)

  2. Servlet - Javascript Pop-up[ Go to top ]

    If you want to display a javascript alert or confirm box without changing the current page displayed, then I would use a hidden frame at the bottom of your page. Set the javascript src property on this frame to the url of your servlet/JSP that generates the message.

    <html>
      <body>
        <img src="image/mygif.gif"
           onclick="document.getElementById('alertFrame').src = 'myPopJsp.jsp'">

        <iframe id="alertFrame" frameborder=0 height=0 width=0
           src="javascript:''"></iframe>
      </body>
    </html>

    Mozilla and crowd do not respond to setting the src property unless the frame originally has a meaningful SRC attribute. Hence the SRC attribute to generate a blank page via javascript.

    The JSP to generate an alert might look like this:

    <html>
      <head>
        <script type="text/javascript"><!--
          function init(){
            alert('<%= myMessage %>');
            window.location.replace('javascript:""');
          }
        //--></script>
      </head>

      <body onload="init();">
      </body>
    </html>

    The window.location.replace() again sets the frame to contain a blank javascript generated page. If you don't do this, then if the user refreshes the page, the alert will appear for a second time. On some browsers it will also remove the hidden page from the history list, so when the user presses the back button for the first time, it doesn't appear to do nothing.

    However, if you don't want a javascript alert(), but want another window to open, I suggest you look at http://developer.netscape.com/viewsource/goodman_modal/goodman_modal.html
  3. Servlet - Javascript Pop-up[ Go to top ]

    Using a hidden iframe like this is also a great way to generate a printer friendly page on the server side, and have the browser print it without having anything popup.

    <html>
      <head>
        <script type="text/javascript"><!--
          function init(){
            focus();
            print();
            window.location.replace('javascript:""');
          }
        //--></script>
      </head>

      <body onload="init();">
      </body>
    </html>

    You must put the focus on the hidden frame for the browser to print the correct frame.