How can I write a HTML-conform String to a new window using a JSP with inner Javascript?   Our Situation:  - Theres a .jsp-File used by a Tomcat-Server  - The .jsp contains a &lt;script language="Javascript&gt;-Tag - this script needs to write a complete, HTML-5-valid-String to a new Window using window.open and 'window'.document.write(htmlString)    Our .jsp-File (schematic):      &lt;%@ include file = "..." %&gt;      &lt;...some page imports...&gt;      &lt;...some scripts...&gt;                     (e.g. &lt;script type = "text/javascript" src="...."&gt; &lt;/script&gt;)      &lt;%       String strMethod = "foo_Method_Bar";      String strOutput = "";      strOutput = someJavaBean-Call_that_brings_valid_html5_string_with_script-Nodes;      %&gt;     ...      &lt;script language="Javascript"&gt;      var strHTML = "&lt;%=strOutput%&gt;";      var win = window.open('','','width=...,height=...');      win.document.write(strHTML);      top.close();      win.focus();      &lt;/script&gt;   Our Problem (schematic):  - .jsp-File gets called.  - .jsp-File calls a JavaBean and sets a global String-Variable to the HTML-String (including  &lt;script&gt;-Tags, DocType-Declarations, etc.)  - .jsp-File replaces all occurrences of the Variable with the obtained String  - javascript (&lt;script&gt;-Tag in the .jsp-File) gets Executed  - &lt;script&gt;-Tag of Javascript is already closed, before 'window'.document.write(strHTML) gets executed, because theres a &lt;/script&gt;-Tag in the Javascript e.g.      &lt;script language="Javascript"&gt;     var strHTML = "&lt;!DOCTYPE html&gt; &lt;html&gt; ... &lt;script&gt; ... &lt;/script&gt; ... &lt;/html&gt;;     var win = window.open(...);     win.document.write(strHTML);     &lt;/script&gt;   - I've searched for quite some time now and I don't have a clue how to solve this issue.  - Writing the HTML-Sourcecode into the Server-File-System and accessing it later on or something like that would be really, really dirty.  - Part of the Problem is that we (of course) have to use this type of javascript-call in the .jsp-File for historical reasons...;-)  - Is there maybe a way to assign the strHTML-Variable in the .jsp-File by Reference only (e.g. without replacing the &lt;%=strOutput%>-Variable)?    Additional Info:  The HTML-String-Generation is used at various places of our programs, multiple times, so i hoped not to have to escape any special CharacterSequences for this particular Call to work.    Appreciate all your help and ideas on this...;-)  Solved: See also  on this issue.
9910
Why do some sites (or advertisers that give clients javascript code) employ a technique of splitting the &lt;script&gt; and/or &lt;/script&gt; tags up within document.write() calls?  I noticed that Amazon does this as well, for example:  &lt;script type='text/javascript'&gt;   if (typeof window['jQuery'] == 'undefined') document.write('&lt;scr'+'ipt type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"&gt;&lt;/sc'+'ript&gt;'); &lt;/script&gt;
8344
I'm working with a bit of html and Javascript code that I've taken over from someone else. The page reloads a table of data (via an asynchronous request) every ten seconds, and then re-builds the table using some DOM code. The code in question looks something like this:  var blah = xmlres.getElementsByTagName('blah'); for(var i = 0; i &lt; blah.length; i++) {     var td = document.createElement('td');     var select = document.createElement('select');     select.setAttribute("...", "...");     select.onchange = function() {         onStatusChanged(select, callid, anotherid);     };     td.appendChild(select); }   When the onchange event is fired for a &lt;select&gt; element however, it seems like the same values are being passed to the onStatusChanged() method for every &lt;select&gt; in the table (I've verified that in each iteration of the loop, callid and anotherid are being given new, distinct values).   I suspect this is occuring because of the nature of how I am setting the event handler, with the select.onchange = function() syntax. If I understand how this is working correctly, this syntax sets a closure for the onchange event to be a function which refers to these two references, which end up having a final value of whatever they are set to on the last iteration of the loop. When the event fires, the value referenced by callid and anotherid is the value set in the last iteration, not the value set at the individual iteration.  Is there a way that I can copy the value of the parameters I am passing to onStatusChanged()?  I've changed the title to better reflect the question and the accepted answer.
11221
When embedding JavaScript in an HTML document, where is the proper place to put the &lt;script&gt; tags and included JavaScript? I seem to recall that you are not supposed to place these in the &lt;head&gt; section, but placing at the beginning of the &lt;body&gt; section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the end of the &lt;body&gt; section as a logical place for &lt;script&gt; tags.  So, where is the right place to put the &lt;script&gt; tags?  (This question references , in which it was suggested that JavaScript function calls should be moved from &lt;a&gt; tags to &lt;script&gt; tags. I'm specifically using jQuery, but more general answers are also appropriate.)
98152
I am trying to customize a Sharepoint 2013 team site.  I created a copy of seattle.master and set it as default master page via context menu.  I added my custom CSS within head tages like so:  &lt;SharePoint:Scriptlink runat="server" Name="https://sharepoint.abc.org/sites/the_new_abc_portal/custom/jquery-1.10.2.min.js" Language="javascript" /&gt;  works!  I added jQuery like so:  &lt;SharePoint:ScriptLink language="javascript" name="/sites/the_new_abc_portal/custom/jquery-1.10.2.min.js" runat="server" Localizable="false" /&gt;  When I reload the page I get:        &lt;html&gt;&lt;head&gt;&lt;META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8"&gt;&lt;meta name="Robots" content="NOINDEX " /&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;       &lt;script type="text/javascript"&gt;                 var gearPage = document.getElementById('GearPage');                 if(null != gearPage)                 {                 gearPage.parentNode.removeChild(gearPage);                 document.title = "Error";                 }             &lt;/script&gt;       &lt;/html&gt;   The link to jQuery is correct.  I now have a solution by which I simply add the normal script tag like so:  &lt;script type="text/javascript" src="/sites/the_new_abc_portal/custom/jquery-1.10.2.min.js"&gt;&lt;/script&gt;  Works like a charm.  Now my questions:   Is there any objection against my "fix" Why doesn't it work in the first place?
76281
I want to do a Response.Redirect("MyPage.aspx") but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how?
26981
I searched all over this site and the web for a good and simple example of autocomplete using jQuery and ASP.NET. I wanted to expose the data used by autocomplete with a webservice (and will probably do that next). In the meantime, I got this working, but it seems a little hacky...  In my page I have a text box:  &lt;input id="txtSearch" type="text" /&gt;   I am using jQuery autocomplete, set up per their example:  &lt;link rel="stylesheet" href="js/jquery.autocomplete.css" type="text/css" /&gt; &lt;script type="text/javascript" src="js/jquery.bgiframe.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery.dimensions.pack.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery.autocomplete.js"&gt;&lt;/script&gt;   Here is where it starts to get hacky... I call a page instead of a webservice:    &lt;script type="text/javascript"&gt;     $(document).ready(function(){         $("#txtSearch").autocomplete('autocompletetagdata.aspx');     });         &lt;/script&gt;   In the page I stripped out ALL of the html and just have this (otherwise, various HTML bits show up in the autocomplete dropdown):  &lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="autocompletetagdata.aspx.cs" Inherits="autocompletetagdata" %&gt;   And in my autocompletetagdata.aspx, I am using SubSonic to query, format and return data from the database (one data item per line):  protected void Page_Load(object sender, EventArgs e) {     // Note the query strings passed by jquery autocomplete:     //QueryString: {q=a&amp;limit=150&amp;timestamp=1227198175320}      LookupTagCollection tags = Select.AllColumnsFrom&lt;LookupTag&gt;()         .Top(Request.QueryString["limit"])         .Where(LookupTag.Columns.TagDescription).Like(Request.QueryString["q"] + "%")         .OrderAsc(LookupTag.Columns.TagDescription)         .ExecuteAsCollection&lt;LookupTagCollection&gt;();      StringBuilder sb = new StringBuilder();      foreach (LookupTag tag in tags)     {         sb.Append(tag.TagDescription).Append("\n");     }      Response.Write(sb.ToString()); }   If you don't do a LIKE query, then it returns everything that contains a match for the character(s) you type -- e.g., typing "a" will include "Ask" and "Answer" as well as "March" and "Mega." I just wanted it to do a starts with match.  Anyway, it works and it's pretty easy to set up, but is there a better way?
24310
I'm trying to get:  document.createElement('div')  //=&gt; true {tagName: 'foobar something'}  //=&gt; false   In my own scripts, I used to just use this since I never needed tagName as a property:  if (!object.tagName) throw ...;   So for the second object, I came up with the following as a quick solution -- which mostly works. ;)  The problem is, it depends on browsers enforcing read-only properties, which not all do.  function isDOM(obj) {   var tag = obj.tagName;   try {     obj.tagName = '';  // Read-only for DOM, should throw exception     obj.tagName = tag; // Restore for normal objects     return false;   } catch (e) {     return true;   } }   Is there a good substitute?
59846
In the following example code, I attach an onclick event handler to the span containing the text "foo". The handler is an anonymous function that pops up an alert().  However, if I assign to the parent node's innerHTML, this onclick event handler gets destroyed - clicking "foo" fails to pop up the alert box.  Is this fixable?  &lt;html&gt;  &lt;head&gt;  &lt;script type="text/javascript"&gt;    function start () {     myspan = document.getElementById("myspan");     myspan.onclick = function() { alert ("hi"); };      mydiv = document.getElementById("mydiv");     mydiv.innerHTML += "bar";   }   &lt;/script&gt;  &lt;/head&gt;   &lt;body onload="start()"&gt;    &lt;div id="mydiv" style="border: solid red 2px"&gt;      &lt;span id="myspan"&gt;foo&lt;/span&gt;    &lt;/div&gt;  &lt;/body&gt;  &lt;/html&gt;
35663
My controller code is as follows -          for(String resStr : responseArray){             if(resStr.indexOf('r_error_str') != -1){                 responseString += resStr.substring(resStr.indexOf('=') + 1);                  responseString += '\n';             }         }   but when i display this 'responseString ' String using 'apex:outputLabel or apex:outputText or as Exception message '\n' is not converting in new line. Whole String is coming in one line.  Can anyone explain why is this happining
75110
I have clicked an image in a slide show and it generates a new window. Once the window opens I need to bring focus on new window and do some stuff. I have attached my code below, but it is not successful.  @Test public void testCreateAccount() throws Exception{  //OPEN manorama online  url driver.navigate().to("http://www.manoramaonline.com/cgi-bin/MMOnline.dll/portal/ep/home.do?tabId=0&amp;BV_ID=@@@");  // to click a link inside a slide show  while (!driver         .findElement(                 By.xpath("/html/body/div[2]/div[2]/div[4]/div/div/div/div/center/div/div[2]/span/div/a/img"))         .isDisplayed()) { } driver.findElement(         By.xpath("/html/body/div[2]/div[2]/div[4]/div/div/div/div/center/div/div[2]/span/div/a/img"))         .click();    String newwindowTitle = driver.getTitle();  switchWindow(newwindowTitle);  }  protected static boolean switchWindow(String title) throws IOException {      String currentWindow = driver.getWindowHandle();     Set&lt;String&gt; availableWindows = driver.getWindowHandles();     if (!availableWindows.isEmpty()) {     for (String windowId : availableWindows) {     if (driver.switchTo().window(windowId).getTitle().equals(title)) {     return true;     } else {         driver.switchTo().window(currentWindow);     }}}      return false;        }
6732
I have a custom search page for use in Customer Portal.  VF Page:    &lt;form name="frmSearch"&gt;      &lt;input type="text" name="keyword" id="keyword" value="{!portalSearchModel.searchTerm}" onkeypress="return noenter(event);" style="width:25%; height:25px;margin:0; padding: 0px 6px 0px;" placeholder="What are you looking for?" /&gt;      &lt;input type="button" id="btnSearch" name="btnSearch" value="Search" onclick="searchTerm()" class="go-we3" /&gt;   &lt;/form&gt;   &lt;script type='text/javascript'&gt;       function searchTerm(){         var searchTerm = document.getElementById("keyword").value;          var url="/apex/PortalSearch?s="+searchTerm;          window.location = url;          return false;     }          &lt;/script&gt;   Is there a way to call this apex method in Controller on button click along with the JavaScript?      public void logSearchTerm(){         portalSearchModel.searches();         Search_Log__c sl = new Search_Log__c();          sl.search_term__c = portalSearchModel.searchTerm;         sl.user__c = UserInfo.getUserId();              insert sl;  }
43302
I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)  Solution Thanks to , I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - SAXException - or just bad IO - IOException.)  public static org.w3c.dom.Document loadXMLFrom(String xml)     throws org.xml.sax.SAXException, java.io.IOException {     return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes())); }  public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is)      throws org.xml.sax.SAXException, java.io.IOException {     javax.xml.parsers.DocumentBuilderFactory factory =         javax.xml.parsers.DocumentBuilderFactory.newInstance();     factory.setNamespaceAware(true);     javax.xml.parsers.DocumentBuilder builder = null;     try {         builder = factory.newDocumentBuilder();     }     catch (javax.xml.parsers.ParserConfigurationException ex) {     }       org.w3c.dom.Document doc = builder.parse(is);     is.close();     return doc; }
37700
How can I strip out extra whitespace from jsp pages' output?  Is there a switch I can flip on my web.xml?  Is there a Tomcat specific setting?
47286
In WebForms, I would normally have code like this to let the browser present a "Download File" popup with an arbitrary file type, like a PDF, and a filename:  Response.Clear() Response.ClearHeaders() ''# Send the file to the output stream Response.Buffer = True  Response.AddHeader("Content-Length", pdfData.Length.ToString()) Response.AddHeader("Content-Disposition", "attachment; filename= " &amp; Server.HtmlEncode(filename))  ''# Set the output stream to the correct content type (PDF). Response.ContentType = "application/pdf"  ''# Output the file Response.BinaryWrite(pdfData)  ''# Flushing the Response to display the serialized data ''# to the client browser. Response.Flush() Response.End()   How do I accomplish the same task in ASP.NET MVC?
120972
My application has javascript button that call Apex code.  Exceptions from web services are sometimes thrown and the user is shown a detailed exception message like this:  A problem with the OnClick JavaScript for this button or link was encountered: {faultcode:'soapenv:Client', faultstring:'HttpException: Example Error Message Class.BananaWebService.fetchBanana: line 22, column 1', }   Is there a simple way to create friendly error messages for my users when exceptions are thrown like this:  Example Error Message   Exception Class  public class HttpException extends Exception{}   Web Service Class   @RestResource(urlMapping='/BananaWebService/*') global class BananaWebService {   webservice static void fetchBanana(Id accountId) {      throw new HttpException('Example Error Message');   } }   Javascript code   {!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")}  {!REQUIRESCRIPT("/soap/ajax/28.0/apex.js")}   var accountId = "{!Account.Id}"; sforce.apex.execute("BananaWebService","fetchBanana", { accountId: accountId });  window.location.reload();
15861
I was wondering if there was some kind of J tool in the java swing library that opens up a file browser window and allows a user to choose a file. Then the ouput of the file would be the absolute path of the chosen file.  Thanks in advance,
58463
Does anyone know of an easy way to escape HTML from strings in ?  I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks).  I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.