public static long injectJavaScript( HttpRequest request, HttpResponse response, InputStream in, OutputStream out, String debugURL) throws IOException { if (!contentTransformations.containsKey("__SELENIUM_JS__")) { init(); } int len = 102400; byte[] buf = new byte[len]; len = readStream(in, buf, len); if (len == -1) { return -1; } int lengthOfBOM = getBOMLength(buf); String data = new String(buf, lengthOfBOM, len); boolean isKnownToBeHtml = HtmlIdentifier.shouldBeInjected(request.getPath(), response.getContentType(), data); String url = response.getHttpRequest().getRequestURL().toString(); if (debugURL.equals(url)) { log.info("debug URL seen"); } if (!isKnownToBeHtml) { out.write(buf, 0, len); } // else if (lengthOfBOM>0) { // out.write(buf, 0, lengthOfBOM); // } String sessionId = SeleniumDriverResourceHandler.getLastSessionId(); long bytesCopied = len; log.fine(url + " (InjectionHelper looking)"); if (!isKnownToBeHtml) { bytesCopied += ModifiedIO.copy(in, out); } else { log.fine("injecting..."); response.removeField("Content-Length"); // added js will make it wrong, lead to page getting // truncated ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (INJECT_SCRIPT_TAGS) { writeScriptTags(baos); } InputStream jsIn = new ClassPathResource(InjectionHelper.injectionHtml).getInputStream(); contentTransformations.put("@SESSION_ID@", sessionId); writeDataWithUserTransformations("", jsIn, baos); jsIn.close(); baos.write(setSomeJsVars(sessionId)); for (String filename : userJsInjectionFiles) { jsIn = new FileInputStream(filename); IO.copy(jsIn, baos); } int headIndex; if (tryToInjectInHead) { headIndex = data.toLowerCase().indexOf("<head>"); } else { headIndex = -1; } if (headIndex != -1) { data = data.substring(0, headIndex + 6) + baos.toString() + data.substring(headIndex + 6); } else { data = baos.toString() + data; } bytesCopied += writeDataWithUserTransformations(data, in, out); } return bytesCopied; }