1 38 package com.gargoylesoftware.htmlunit.html; 39 40 import java.util.Map ; 41 42 43 60 public class HtmlScript extends HtmlElement { 61 62 63 public static final String TAG_NAME = "script"; 64 private static int EventHandlerId_; 65 66 72 public HtmlScript( final HtmlPage page, final Map attributes ) { 73 super(page, attributes); 74 } 75 76 79 public String getTagName() { 80 return TAG_NAME; 81 } 82 83 91 public final String getCharsetAttribute() { 92 return getAttributeValue("charset"); 93 } 94 95 96 104 public final String getTypeAttribute() { 105 return getAttributeValue("type"); 106 } 107 108 109 117 public final String getLanguageAttribute() { 118 return getAttributeValue("language"); 119 } 120 121 122 130 public final String getSrcAttribute() { 131 return getAttributeValue("src"); 132 } 133 134 138 public final String getEventAttribute() { 139 return getAttributeValue("event"); 140 } 141 142 146 public final String getHtmlForAttribute() { 147 return getAttributeValue("for"); 148 } 149 150 158 public final String getDeferAttribute() { 159 return getAttributeValue("defer"); 160 } 161 162 166 public DomNode appendChild(final DomNode node) { 167 final DomNode response = super.appendChild(node); 168 executeScriptIfNeeded(); 169 return response; 170 } 171 172 175 void executeScriptIfNeeded() { 176 final HtmlPage page = getPage(); 177 178 if (!page.getWebClient().isJavaScriptEnabled()) { 179 return; 180 } 181 if (!HtmlPage.isJavaScript(getTypeAttribute(), getLanguageAttribute())) { 182 getLog().debug("Script is not javascript. Skipping execution."); 183 return; 184 } 185 186 if (getSrcAttribute() != HtmlElement.ATTRIBUTE_NOT_DEFINED) { 187 getLog().debug("Loading external javascript: " + getSrcAttribute()); 188 page.loadExternalJavaScriptFile(getSrcAttribute(), getCharsetAttribute()); 189 } 190 else if (getFirstChild() != null) { 191 final DomCharacterData textNode = (DomCharacterData) getFirstChild(); 192 final String scriptCode; 193 if (getEventAttribute() != ATTRIBUTE_NOT_DEFINED 194 && getHtmlForAttribute() != ATTRIBUTE_NOT_DEFINED) { 195 String eventName = getEventAttribute(); 197 if (eventName.endsWith("()")) { 198 eventName = eventName.substring(0, eventName.length()-2); 199 } 200 final String scriptEventHandler = getHtmlForAttribute() + "." + eventName; 201 final String evhName = "htmlunit_evh_JJLL" + EventHandlerId_; 202 scriptCode = "function " + evhName + "()\n{" 203 + textNode.getData() + "}\n" 204 + scriptEventHandler + "=" + evhName + ";"; 205 } 206 else { 207 scriptCode = textNode.getData(); 208 } 209 getPage().executeJavaScriptIfPossible(scriptCode, "Embedded script", false, null); 210 } 211 } 212 } 213 | Popular Tags |