com.gargoylesoftware.htmlunit.javascript.host.Window Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of htmlunit Show documentation
Show all versions of htmlunit Show documentation
A headless browser intended for use in testing web-based applications.
/*
* Copyright (c) 2002-2022 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gargoylesoftware.htmlunit.javascript.host;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_CHANGE_OPENER_ONLY_WINDOW_OBJECT;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_FORMFIELDS_ACCESSIBLE_BY_NAME;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_FRAMES_ACCESSIBLE_BY_ID;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_FRAME_BY_ID_RETURNS_WINDOW;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_SELECTION_NULL_IF_INVISIBLE;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_TOP_WRITABLE;
import static com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.CHROME;
import static com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.EDGE;
import static com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.FF;
import static com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.FF_ESR;
import static com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.IE;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.gargoylesoftware.htmlunit.AlertHandler;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.ConfirmHandler;
import com.gargoylesoftware.htmlunit.DialogWindow;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.PromptHandler;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.SgmlPage;
import com.gargoylesoftware.htmlunit.StatusHandler;
import com.gargoylesoftware.htmlunit.StorageHolder.Type;
import com.gargoylesoftware.htmlunit.TopLevelWindow;
import com.gargoylesoftware.htmlunit.WebAssert;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.WebWindowNotFoundException;
import com.gargoylesoftware.htmlunit.html.BaseFrameElement;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.FrameWindow;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlAttributeChangeEvent;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlEmbed;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlFrame;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlMap;
import com.gargoylesoftware.htmlunit.html.HtmlObject;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.html.HtmlTextArea;
import com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine;
import com.gargoylesoftware.htmlunit.javascript.PostponedAction;
import com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass;
import com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstant;
import com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstructor;
import com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction;
import com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter;
import com.gargoylesoftware.htmlunit.javascript.configuration.JsxSetter;
import com.gargoylesoftware.htmlunit.javascript.host.crypto.Crypto;
import com.gargoylesoftware.htmlunit.javascript.host.css.CSS2Properties;
import com.gargoylesoftware.htmlunit.javascript.host.css.MediaQueryList;
import com.gargoylesoftware.htmlunit.javascript.host.css.StyleMedia;
import com.gargoylesoftware.htmlunit.javascript.host.dom.Document;
import com.gargoylesoftware.htmlunit.javascript.host.dom.Selection;
import com.gargoylesoftware.htmlunit.javascript.host.event.Event;
import com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget;
import com.gargoylesoftware.htmlunit.javascript.host.event.MessageEvent;
import com.gargoylesoftware.htmlunit.javascript.host.event.MouseEvent;
import com.gargoylesoftware.htmlunit.javascript.host.html.DataTransfer;
import com.gargoylesoftware.htmlunit.javascript.host.html.DocumentProxy;
import com.gargoylesoftware.htmlunit.javascript.host.html.HTMLCollection;
import com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument;
import com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement;
import com.gargoylesoftware.htmlunit.javascript.host.performance.Performance;
import com.gargoylesoftware.htmlunit.javascript.host.speech.SpeechSynthesis;
import com.gargoylesoftware.htmlunit.javascript.host.xml.XMLDocument;
import com.gargoylesoftware.htmlunit.util.UrlUtils;
import com.gargoylesoftware.htmlunit.xml.XmlPage;
import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.ContextAction;
import net.sourceforge.htmlunit.corejs.javascript.ContextFactory;
import net.sourceforge.htmlunit.corejs.javascript.EcmaError;
import net.sourceforge.htmlunit.corejs.javascript.Function;
import net.sourceforge.htmlunit.corejs.javascript.JavaScriptException;
import net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime;
import net.sourceforge.htmlunit.corejs.javascript.Scriptable;
import net.sourceforge.htmlunit.corejs.javascript.ScriptableObject;
import net.sourceforge.htmlunit.corejs.javascript.Undefined;
/**
* A JavaScript object for {@code Window}.
*
* @author Mike Bowler
* @author Chen Jun
* @author David K. Taylor
* @author Christian Sell
* @author Darrell DeBoer
* @author Marc Guillemot
* @author Dierk Koenig
* @author Daniel Gredler
* @author David D. Kilzer
* @author Chris Erskine
* @author Ahmed Ashour
* @author Ronald Brill
* @author Frank Danek
* @author Carsten Steul
* @author Colin Alworth
* @author Atsushi Nakagawa
* @see MSDN documentation
*/
@JsxClass
public class Window extends EventTarget implements WindowOrWorkerGlobalScope, Function, AutoCloseable {
private static final Log LOG = LogFactory.getLog(Window.class);
/** To be documented. */
@JsxConstant({CHROME, EDGE})
public static final short TEMPORARY = 0;
/** To be documented. */
@JsxConstant({CHROME, EDGE})
public static final short PERSISTENT = 1;
private Document document_;
private DocumentProxy documentProxy_;
private Navigator navigator_;
private Object clientInformation_;
private WebWindow webWindow_;
private WindowProxy windowProxy_;
private Screen screen_;
private History history_;
private Location location_;
private ScriptableObject console_;
private ApplicationCache applicationCache_;
private Selection selection_;
private Event currentEvent_;
private String status_ = "";
private Map, Scriptable> prototypes_ = new HashMap<>();
private Map prototypesPerJSName_ = new HashMap<>();
private Object controllers_;
private Object opener_;
private Object top_ = NOT_FOUND; // top can be set from JS to any value!
private Crypto crypto_;
private final EnumMap storages_ = new EnumMap<>(Type.class);
private transient List animationFrames_ = new ArrayList<>();
private static final class AnimationFrame {
private final long id_;
private final Function callback_;
AnimationFrame(final long id, final Function callback) {
id_ = id;
callback_ = callback;
}
}
/**
* Creates an instance.
*/
public Window() {
}
/**
* Creates an instance.
*
* @param cx the current context
* @param args the arguments to the ActiveXObject constructor
* @param ctorObj the function object
* @param inNewExpr Is new or not
* @return the java object to allow JavaScript to access
*/
@JsxConstructor({CHROME, EDGE, FF, FF_ESR})
public static Scriptable jsConstructor(final Context cx, final Object[] args, final Function ctorObj,
final boolean inNewExpr) {
throw ScriptRuntime.typeError("Illegal constructor");
}
/**
* Restores the transient fields during deserialization.
* @param stream the stream to read the object from
* @throws IOException if an IO error occurs
* @throws ClassNotFoundException if a class is not found
*/
private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
animationFrames_ = new ArrayList<>();
}
/**
* Returns the prototype object corresponding to the specified HtmlUnit class inside the window scope.
* @param jsClass the class whose prototype is to be returned
* @return the prototype object corresponding to the specified class inside the specified scope
*/
@Override
public Scriptable getPrototype(final Class extends HtmlUnitScriptable> jsClass) {
return prototypes_.get(jsClass);
}
/**
* Returns the prototype object corresponding to the specified HtmlUnit class inside the window scope.
* @param className the class name whose prototype is to be returned
* @return the prototype object corresponding to the specified class inside the specified scope
*/
public Scriptable getPrototype(final String className) {
return prototypesPerJSName_.get(className);
}
/**
* Sets the prototypes for HtmlUnit host classes.
* @param map a Map of ({@link Class}, {@link Scriptable})
* @param prototypesPerJSName map of {@link String} and {@link Scriptable}
*/
public void setPrototypes(final Map, Scriptable> map,
final Map prototypesPerJSName) {
prototypes_ = map;
prototypesPerJSName_ = prototypesPerJSName;
}
/**
* The JavaScript function {@code alert()}.
* @param message the message
*/
@JsxFunction
public void alert(final Object message) {
// use Object as parameter and perform String conversion by ourself
// this allows to place breakpoint here and "see" the message object and its properties
final String stringMessage = Context.toString(message);
final AlertHandler handler = getWebWindow().getWebClient().getAlertHandler();
if (handler == null) {
if (LOG.isWarnEnabled()) {
LOG.warn("window.alert(\"" + stringMessage + "\") no alert handler installed");
}
}
else {
handler.handleAlert(document_.getPage(), stringMessage);
}
}
/**
* Creates a base-64 encoded ASCII string from a string of binary data.
* @param stringToEncode string to encode
* @return the encoded string
*/
@JsxFunction
@Override
public String btoa(final String stringToEncode) {
return WindowOrWorkerGlobalScopeMixin.btoa(stringToEncode);
}
/**
* Decodes a string of data which has been encoded using base-64 encoding.
* @param encodedData the encoded string
* @return the decoded value
*/
@JsxFunction
@Override
public String atob(final String encodedData) {
return WindowOrWorkerGlobalScopeMixin.atob(encodedData);
}
/**
* The JavaScript function {@code confirm}.
* @param message the message
* @return true if ok was pressed, false if cancel was pressed
*/
@JsxFunction
public boolean confirm(final String message) {
final ConfirmHandler handler = getWebWindow().getWebClient().getConfirmHandler();
if (handler == null) {
if (LOG.isWarnEnabled()) {
LOG.warn("window.confirm(\""
+ message + "\") no confirm handler installed, simulating the OK button");
}
return true;
}
return handler.handleConfirm(document_.getPage(), message);
}
/**
* The JavaScript function {@code prompt}.
* @param message the message
* @param defaultValue the default value displayed in the text input field
* @return the value typed in or {@code null} if the user pressed {@code cancel}
*/
@JsxFunction
public String prompt(final String message, Object defaultValue) {
final PromptHandler handler = getWebWindow().getWebClient().getPromptHandler();
if (handler == null) {
if (LOG.isWarnEnabled()) {
LOG.warn("window.prompt(\"" + message + "\") no prompt handler installed");
}
return null;
}
if (Undefined.isUndefined(defaultValue)) {
defaultValue = null;
}
else {
defaultValue = Context.toString(defaultValue);
}
return handler.handlePrompt(document_.getPage(), message, (String) defaultValue);
}
/**
* Returns the JavaScript property {@code document}.
* @return the document
*/
@JsxGetter(propertyName = "document")
public DocumentProxy getDocument_js() {
return documentProxy_;
}
/**
* Returns the window's current document.
* @return the window's current document
*/
public Document getDocument() {
return document_;
}
/**
* Returns the application cache.
* @return the application cache
*/
@JsxGetter({FF, FF_ESR, IE})
public ApplicationCache getApplicationCache() {
return applicationCache_;
}
/**
* Returns the current event.
* @return the current event, or {@code null} if no event is currently available
*/
@JsxGetter
public Object getEvent() {
return currentEvent_;
}
/**
* Returns the current event (used internally regardless of the emulation mode).
* @return the current event, or {@code null} if no event is currently available
*/
public Event getCurrentEvent() {
return currentEvent_;
}
/**
* Sets the current event.
* @param event the current event
*/
public void setCurrentEvent(final Event event) {
currentEvent_ = event;
}
/**
* Opens a new window.
*
* @param url when a new document is opened, url is a String that specifies a MIME type for the document.
* When a new window is opened, url is a String that specifies the URL to render in the new window
* @param name the name
* @param features the features
* @param replace whether to replace in the history list or no
* @return the newly opened window, or {@code null} if popup windows have been disabled
* @see com.gargoylesoftware.htmlunit.WebClientOptions#isPopupBlockerEnabled()
* @see MSDN documentation
*/
@JsxFunction
public WindowProxy open(final Object url, final Object name, final Object features,
final Object replace) {
String urlString = null;
if (!Undefined.isUndefined(url)) {
urlString = Context.toString(url);
}
String windowName = "";
if (!Undefined.isUndefined(name)) {
windowName = Context.toString(name);
}
String featuresString = null;
if (!Undefined.isUndefined(features)) {
featuresString = Context.toString(features);
}
final WebClient webClient = getWebWindow().getWebClient();
if (webClient.getOptions().isPopupBlockerEnabled()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Ignoring window.open() invocation because popups are blocked.");
}
return null;
}
boolean replaceCurrentEntryInBrowsingHistory = false;
if (!Undefined.isUndefined(replace)) {
replaceCurrentEntryInBrowsingHistory = Context.toBoolean(replace);
}
if ((featuresString != null || replaceCurrentEntryInBrowsingHistory) && LOG.isDebugEnabled()) {
LOG.debug(
"window.open: features and replaceCurrentEntryInBrowsingHistory "
+ "not implemented: url=[" + urlString
+ "] windowName=[" + windowName
+ "] features=[" + featuresString
+ "] replaceCurrentEntry=[" + replaceCurrentEntryInBrowsingHistory
+ "]");
}
// if specified name is the name of an existing window, then hold it
if (StringUtils.isEmpty(urlString) && !"".equals(windowName)) {
try {
final WebWindow webWindow = webClient.getWebWindowByName(windowName);
return getProxy(webWindow);
}
catch (final WebWindowNotFoundException e) {
// nothing
}
}
final URL newUrl = makeUrlForOpenWindow(urlString);
final WebWindow newWebWindow = webClient.openWindow(newUrl, windowName, webWindow_);
return getProxy(newWebWindow);
}
private URL makeUrlForOpenWindow(final String urlString) {
if (urlString.isEmpty()) {
return UrlUtils.URL_ABOUT_BLANK;
}
try {
final Page page = getWebWindow().getEnclosedPage();
if (page != null && page.isHtmlPage()) {
return ((HtmlPage) page).getFullyQualifiedUrl(urlString);
}
return new URL(urlString);
}
catch (final MalformedURLException e) {
if (LOG.isWarnEnabled()) {
LOG.error("Unable to create URL for openWindow: relativeUrl=[" + urlString + "]", e);
}
return null;
}
}
/**
* Sets a chunk of JavaScript to be invoked at some specified time later.
* The invocation occurs only if the window is opened after the delay
* and does not contain an other page than the one that originated the setTimeout.
*
* @see
* MDN web docs
*
* @param context the JavaScript context
* @param thisObj the scriptable
* @param args the arguments passed into the method
* @param function the function
* @return the id of the created timer
*/
@JsxFunction
public static Object setTimeout(final Context context, final Scriptable thisObj,
final Object[] args, final Function function) {
return WindowOrWorkerGlobalScopeMixin.setTimeout(context, thisObj, args, function);
}
/**
* Sets a chunk of JavaScript to be invoked each time a specified number of milliseconds has elapsed.
*
* @see
* MDN web docs
* @param context the JavaScript context
* @param thisObj the scriptable
* @param args the arguments passed into the method
* @param function the function
* @return the id of the created interval
*/
@JsxFunction
public static Object setInterval(final Context context, final Scriptable thisObj,
final Object[] args, final Function function) {
return WindowOrWorkerGlobalScopeMixin.setInterval(context, thisObj, args, function);
}
/**
* Cancels a time-out previously set with the
* {@link #setTimeout(Context, Scriptable, Object[], Function)} method.
*
* @param timeoutId identifier for the timeout to clear
* as returned by {@link #setTimeout(Context, Scriptable, Object[], Function)}
*/
@JsxFunction
public void clearTimeout(final int timeoutId) {
if (LOG.isDebugEnabled()) {
LOG.debug("clearTimeout(" + timeoutId + ")");
}
getWebWindow().getJobManager().removeJob(timeoutId);
}
/**
* Cancels the interval previously started using the
* {@link #setInterval(Context, Scriptable, Object[], Function)} method.
* Current implementation does nothing.
* @param intervalID specifies the interval to cancel as returned by the
* {@link #setInterval(Context, Scriptable, Object[], Function)} method
* @see MSDN documentation
*/
@JsxFunction
public void clearInterval(final int intervalID) {
if (LOG.isDebugEnabled()) {
LOG.debug("clearInterval(" + intervalID + ")");
}
getWebWindow().getJobManager().removeJob(intervalID);
}
/**
* Returns the JavaScript property {@code navigator}.
* @return the navigator
*/
@JsxGetter
public Navigator getNavigator() {
return navigator_;
}
/**
* Returns the JavaScript property {@code clientInformation}.
* @return the client information
*/
@JsxGetter({CHROME, EDGE, FF, FF_ESR, IE})
public Object getClientInformation() {
if (clientInformation_ != null) {
return clientInformation_;
}
return navigator_;
}
/**
* @param clientInformation the new value
*/
@JsxSetter({CHROME, EDGE})
public void setClientInformation(final Object clientInformation) {
clientInformation_ = clientInformation;
}
/**
* Returns the JavaScript property {@code clipboardData}.
* @return the {@link DataTransfer}
*/
@JsxGetter(IE)
public DataTransfer getClipboardData() {
final DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setParentScope(this);
dataTransfer.setPrototype(getPrototype(dataTransfer.getClass()));
return dataTransfer;
}
/**
* Returns the window property. This is a synonym for {@code self}.
* @return the window property (a reference to this)
*/
@JsxGetter(propertyName = "window")
public Window getWindow_js() {
return this;
}
/**
* Returns the {@code self} property.
* @return this
*/
@JsxGetter
public Window getSelf() {
return this;
}
/**
* Returns the {@code localStorage} property.
* @return the {@code localStorage} property
*/
@JsxGetter
public Storage getLocalStorage() {
return getStorage(Type.LOCAL_STORAGE);
}
/**
* Returns the {@code sessionStorage} property.
* @return the {@code sessionStorage} property
*/
@JsxGetter
public Storage getSessionStorage() {
return getStorage(Type.SESSION_STORAGE);
}
/**
* Gets the storage of the specified type.
* @param storageType the type
* @return the storage
*/
public Storage getStorage(final Type storageType) {
return storages_.computeIfAbsent(storageType,
k -> {
final WebWindow webWindow = getWebWindow();
final Map store = webWindow.getWebClient().getStorageHolder().
getStore(storageType, webWindow.getEnclosedPage());
return new Storage(this, store);
}
);
}
/**
* Returns the {@code location} property.
* @return the {@code location} property
*/
@JsxGetter
public Location getLocation() {
return location_;
}
/**
* Sets the {@code location} property. This will cause a reload of the window.
* @param newLocation the URL of the new content
* @throws IOException when location loading fails
*/
@JsxSetter
public void setLocation(final String newLocation) throws IOException {
location_.setHref(newLocation);
}
/**
* Returns the {@code console} property.
* @return the {@code console} property
*/
@JsxGetter
public ScriptableObject getConsole() {
return console_;
}
/**
* Sets the {@code console}.
* @param console the console
*/
@JsxSetter
public void setConsole(final ScriptableObject console) {
console_ = console;
}
/**
* Prints messages to the {@code console}.
* @param message the message to log
*/
@JsxFunction({FF, FF_ESR})
public void dump(final String message) {
if (console_ instanceof Console) {
Console.log(null, console_, new Object[] {message}, null);
}
}
/**
* Invokes all the animation callbacks registered for this window by
* calling {@link #requestAnimationFrame(Object)} once.
* @return the number of pending animation callbacks
*/
public int animateAnimationsFrames() {
final List animationFrames = new ArrayList<>(animationFrames_);
animationFrames_.clear();
final double now = System.nanoTime() / 1_000_000d;
final Object[] args = {now};
final WebWindow ww = getWindow().getWebWindow();
final JavaScriptEngine jsEngine = (JavaScriptEngine) ww.getWebClient().getJavaScriptEngine();
for (final AnimationFrame animationFrame : animationFrames) {
jsEngine.callFunction((HtmlPage) ww.getEnclosedPage(),
animationFrame.callback_, this, getParentScope(), args);
}
return animationFrames_.size();
}
/**
* Add callback to the list of animationFrames.
* @param callback the function to call when it's time to update the animation
* @return an identification id
* @see MDN Doc
*/
@JsxFunction
public int requestAnimationFrame(final Object callback) {
if (callback instanceof Function) {
final int id = animationFrames_.size();
final AnimationFrame animationFrame = new AnimationFrame(id, (Function) callback);
animationFrames_.add(animationFrame);
return id;
}
return -1;
}
/**
* Remove the callback from the list of animationFrames.
* @param requestId the ID value returned by the call to window.requestAnimationFrame()
* @see MDN Doc
*/
@JsxFunction
public void cancelAnimationFrame(final Object requestId) {
final int id = (int) Context.toNumber(requestId);
animationFrames_.removeIf(animationFrame -> animationFrame.id_ == id);
}
/**
* Returns the {@code screen} property.
* @return the {@code screen} property
*/
@JsxGetter
public Screen getScreen() {
return screen_;
}
/**
* Returns the {@code history} property.
* @return the {@code history} property
*/
@JsxGetter
public History getHistory() {
return history_;
}
/**
* Returns the {@code external} property.
* @return the {@code external} property
*/
@JsxGetter
public External getExternal() {
final External external = new External();
external.setParentScope(this);
external.setPrototype(getPrototype(external.getClass()));
return external;
}
/**
* Initializes this window.
* @param webWindow the web window corresponding to this window
* @param pageToEnclose the page that will become the enclosing page
*/
public void initialize(final WebWindow webWindow, final Page pageToEnclose) {
webWindow_ = webWindow;
webWindow_.setScriptableObject(this);
windowProxy_ = new WindowProxy(webWindow_);
if (pageToEnclose instanceof XmlPage) {
document_ = new XMLDocument();
}
else {
document_ = new HTMLDocument();
}
document_.setParentScope(this);
document_.setPrototype(getPrototype(document_.getClass()));
document_.setWindow(this);
if (pageToEnclose instanceof SgmlPage) {
final SgmlPage page = (SgmlPage) pageToEnclose;
document_.setDomNode(page);
if (page.isHtmlPage()) {
final HtmlPage htmlPage = (HtmlPage) page;
htmlPage.addAutoCloseable(this);
}
}
documentProxy_ = new DocumentProxy(webWindow_);
navigator_ = new Navigator();
navigator_.setParentScope(this);
navigator_.setPrototype(getPrototype(navigator_.getClass()));
screen_ = new Screen(getWebWindow().getScreen());
screen_.setParentScope(this);
screen_.setPrototype(getPrototype(screen_.getClass()));
history_ = new History();
history_.setParentScope(this);
history_.setPrototype(getPrototype(history_.getClass()));
location_ = new Location();
location_.setParentScope(this);
location_.setPrototype(getPrototype(location_.getClass()));
location_.initialize(this, pageToEnclose);
final Console console = new Console();
console.setWebWindow(webWindow_);
console.setParentScope(this);
console.setPrototype(getPrototype(console.getClass()));
console_ = console;
applicationCache_ = new ApplicationCache();
applicationCache_.setParentScope(this);
applicationCache_.setPrototype(getPrototype(applicationCache_.getClass()));
// like a JS new Object()
final Context ctx = Context.getCurrentContext();
controllers_ = ctx.newObject(this);
if (webWindow_ instanceof TopLevelWindow) {
final WebWindow opener = ((TopLevelWindow) webWindow_).getOpener();
if (opener != null) {
opener_ = opener.getScriptableObject();
}
}
}
/**
* Initialize the object.
* @param enclosedPage the page containing the JavaScript
*/
public void initialize(final Page enclosedPage) {
if (enclosedPage != null && enclosedPage.isHtmlPage()) {
final HtmlPage htmlPage = (HtmlPage) enclosedPage;
// Windows don't have corresponding DomNodes so set the domNode
// variable to be the page. If this isn't set then HtmlUnitScriptable.get()
// won't work properly
setDomNode(htmlPage);
clearEventListenersContainer();
WebAssert.notNull("document_", document_);
document_.setDomNode(htmlPage);
}
}
/**
* Initializes the object. Only called for Windows with no contents.
*/
public void initialize() {
// Empty.
}
/**
* Returns the value of the {@code top} property.
* @return the value of {@code top}
*/
@JsxGetter
public Object getTop() {
if (top_ != NOT_FOUND) {
return top_;
}
final WebWindow top = getWebWindow().getTopWindow();
return top.getScriptableObject();
}
/**
* Sets the value of the {@code top} property.
* @param o the new value
*/
@JsxSetter
public void setTop(final Object o) {
if (getBrowserVersion().hasFeature(JS_WINDOW_TOP_WRITABLE)) {
top_ = o;
}
}
/**
* Returns the value of the {@code parent} property.
* @return the value of the {@code parent} property
*/
@JsxGetter
public ScriptableObject getParent() {
final WebWindow parent = getWebWindow().getParentWindow();
return parent.getScriptableObject();
}
/**
* Returns the value of the {@code opener} property.
* @return the value of the {@code opener}, or {@code null} for a top level window
*/
@JsxGetter
public Object getOpener() {
Object opener = opener_;
if (opener instanceof Window) {
opener = ((Window) opener).windowProxy_;
}
return opener;
}
/**
* Sets the {@code opener} property.
* @param newValue the new value
*/
@JsxSetter
public void setOpener(final Object newValue) {
if (getBrowserVersion().hasFeature(JS_WINDOW_CHANGE_OPENER_ONLY_WINDOW_OBJECT)
&& newValue != null && !Undefined.isUndefined(newValue) && !(newValue instanceof Window)) {
throw Context.reportRuntimeError("Can't set opener to something other than a window!");
}
opener_ = newValue;
}
/**
* Returns the (i)frame in which the window is contained.
* @return {@code null} for a top level window
*/
@JsxGetter
public Object getFrameElement() {
final WebWindow window = getWebWindow();
if (window instanceof FrameWindow) {
return ((FrameWindow) window).getFrameElement().getScriptableObject();
}
return null;
}
/**
* Returns the value of the {@code frames} property.
* @return the value of the {@code frames} property
*/
@JsxGetter(propertyName = "frames")
public Window getFrames_js() {
return this;
}
/**
* Returns the number of frames contained by this window.
* @return the number of frames contained by this window
*/
@JsxGetter
public int getLength() {
final HTMLCollection frames = getFrames();
if (frames != null) {
return frames.getLength();
}
return 0;
}
/**
* Returns the live collection of frames contained by this window.
* @return the live collection of frames contained by this window
*/
private HTMLCollection getFrames() {
final Page page = getWebWindow().getEnclosedPage();
if (page instanceof HtmlPage) {
return new HTMLCollectionFrames((HtmlPage) page);
}
return null;
}
/**
* Returns the WebWindow associated with this Window.
* @return the WebWindow
*/
public WebWindow getWebWindow() {
return webWindow_;
}
/**
* Sets the focus to this element.
*/
@JsxFunction
public void focus() {
final WebWindow window = getWebWindow();
window.getWebClient().setCurrentWindow(window);
}
/**
* Removes focus from this element.
*/
@JsxFunction
public void blur() {
if (LOG.isDebugEnabled()) {
LOG.debug("window.blur() not implemented");
}
}
/**
* Closes this window.
*/
@JsxFunction(functionName = "close")
public void close_js() {
final WebWindow webWindow = getWebWindow();
if (webWindow instanceof TopLevelWindow) {
((TopLevelWindow) webWindow).close();
}
else {
webWindow.getWebClient().deregisterWebWindow(webWindow);
}
}
/**
* Indicates if this window is closed.
* @return {@code true} if this window is closed
*/
@JsxGetter
public boolean isClosed() {
final WebWindow webWindow = getWebWindow();
return !webWindow.getWebClient().containsWebWindow(webWindow);
}
/**
* Does nothing.
* @param x the horizontal position
* @param y the vertical position
*/
@JsxFunction
public void moveTo(final int x, final int y) {
if (LOG.isDebugEnabled()) {
LOG.debug("window.moveTo() not implemented");
}
}
/**
* Does nothing.
* @param x the horizontal position
* @param y the vertical position
*/
@JsxFunction
public void moveBy(final int x, final int y) {
if (LOG.isDebugEnabled()) {
LOG.debug("window.moveBy() not implemented");
}
}
/**
* Loads the new HTML document corresponding to the specified URL.
* @param url the location of the new HTML document to load
* @throws IOException if loading the specified location fails
* @see MSDN Documentation
*/
@JsxFunction(IE)
public void navigate(final String url) throws IOException {
getLocation().assign(url);
}
/**
* Does nothing.
* @param width the width offset
* @param height the height offset
*/
@JsxFunction
public void resizeBy(final int width, final int height) {
if (LOG.isDebugEnabled()) {
LOG.debug("window.resizeBy() not implemented");
}
}
/**
* Does nothing.
* @param width the width of the Window in pixel after resize
* @param height the height of the Window in pixel after resize
*/
@JsxFunction
public void resizeTo(final int width, final int height) {
if (LOG.isDebugEnabled()) {
LOG.debug("window.resizeTo() not implemented");
}
}
/**
* Scrolls to the specified location on the page.
* @param x the horizontal position to scroll to
* @param y the vertical position to scroll to
*/
@JsxFunction
public void scroll(final int x, final int y) {
scrollTo(x, y);
}
/**
* Scrolls the window content the specified distance.
* @param x the horizontal distance to scroll by
* @param y the vertical distance to scroll by
*/
@JsxFunction
public void scrollBy(final int x, final int y) {
final HTMLElement body = document_.getBody();
if (body != null) {
body.setScrollLeft(body.getScrollLeft() + x);
body.setScrollTop(body.getScrollTop() + y);
final Event event = new Event(body, Event.TYPE_SCROLL);
body.fireEvent(event);
}
}
/**
* Scrolls the window content down by the specified number of lines.
* @param lines the number of lines to scroll down
*/
@JsxFunction({FF, FF_ESR})
public void scrollByLines(final int lines) {
final HTMLElement body = document_.getBody();
if (body != null) {
body.setScrollTop(body.getScrollTop() + (19 * lines));
final Event event = new Event(body, Event.TYPE_SCROLL);
body.fireEvent(event);
}
}
/**
* Scrolls the window content down by the specified number of pages.
* @param pages the number of pages to scroll down
*/
@JsxFunction({FF, FF_ESR})
public void scrollByPages(final int pages) {
final HTMLElement body = document_.getBody();
if (body != null) {
body.setScrollTop(body.getScrollTop() + (getInnerHeight() * pages));
final Event event = new Event(body, Event.TYPE_SCROLL);
body.fireEvent(event);
}
}
/**
* Scrolls to the specified location on the page.
* @param x the horizontal position to scroll to
* @param y the vertical position to scroll to
*/
@JsxFunction
public void scrollTo(final int x, final int y) {
final HTMLElement body = document_.getBody();
if (body != null) {
body.setScrollLeft(x);
body.setScrollTop(y);
final Event event = new Event(body, Event.TYPE_SCROLL);
body.fireEvent(event);
}
}
/**
* Returns the {@code onload} property. Note that this is not necessarily a function if something else has been set.
* @return the {@code onload} property
*/
@JsxGetter
public Object getOnload() {
return getEventHandler(Event.TYPE_LOAD);
}
/**
* Sets the value of the {@code onload} event handler.
* @param onload the new handler
*/
@JsxSetter
public void setOnload(final Object onload) {
setHandlerForJavaScript(Event.TYPE_LOAD, onload);
}
/**
* Sets the value of the {@code onblur} event handler.
* @param onblur the new handler
*/
@JsxSetter
public void setOnblur(final Object onblur) {
setHandlerForJavaScript(Event.TYPE_BLUR, onblur);
}
/**
* Returns the {@code onblur} property (not necessary a function if something else has been set).
* @return the {@code onblur} property
*/
@JsxGetter
public Object getOnblur() {
return getEventHandler(Event.TYPE_BLUR);
}
/**
* Returns the {@code onclick} property (not necessary a function if something else has been set).
* @return the {@code onclick} property
*/
@JsxGetter
public Object getOnclick() {
return getEventHandler(MouseEvent.TYPE_CLICK);
}
/**
* Sets the value of the {@code onclick} event handler.
* @param onclick the new handler
*/
@JsxSetter
public void setOnclick(final Object onclick) {
setHandlerForJavaScript(MouseEvent.TYPE_CLICK, onclick);
}
/**
* Returns the {@code ondblclick} property (not necessary a function if something else has been set).
* @return the {@code ondblclick} property
*/
@JsxGetter
public Object getOndblclick() {
return getEventHandler(MouseEvent.TYPE_DBL_CLICK);
}
/**
* Sets the value of the {@code ondblclick} event handler.
* @param ondblclick the new handler
*/
@JsxSetter
public void setOndblclick(final Object ondblclick) {
setHandlerForJavaScript(MouseEvent.TYPE_DBL_CLICK, ondblclick);
}
/**
* Returns the {@code onhashchange} property (not necessary a function if something else has been set).
* @return the {@code onhashchange} property
*/
@JsxGetter
public Object getOnhashchange() {
return getEventHandler(Event.TYPE_HASH_CHANGE);
}
/**
* Sets the value of the {@code onhashchange} event handler.
* @param onhashchange the new handler
*/
@JsxSetter
public void setOnhashchange(final Object onhashchange) {
setHandlerForJavaScript(Event.TYPE_HASH_CHANGE, onhashchange);
}
/**
* Returns the value of the window's {@code name} property.
* @return the value of the window's {@code name} property
*/
@JsxGetter
public String getName() {
return getWebWindow().getName();
}
/**
* Sets the value of the window's {@code name} property.
* @param name the value of the window's {@code name} property
*/
@JsxSetter
public void setName(final String name) {
getWebWindow().setName(name);
}
/**
* Returns the value of the window's {@code onbeforeunload} property.
* @return the value of the window's {@code onbeforeunload} property
*/
@JsxGetter
public Object getOnbeforeunload() {
return getEventHandler(Event.TYPE_BEFORE_UNLOAD);
}
/**
* Sets the value of the window's {@code onbeforeunload} property.
* @param onbeforeunload the value of the window's {@code onbeforeunload} property
*/
@JsxSetter
public void setOnbeforeunload(final Object onbeforeunload) {
setHandlerForJavaScript(Event.TYPE_BEFORE_UNLOAD, onbeforeunload);
}
/**
* Returns the value of the window's {@code onerror} property.
* @return the value of the window's {@code onerror} property
*/
@JsxGetter
public Object getOnerror() {
return getEventHandler(Event.TYPE_ERROR);
}
/**
* Sets the value of the window's {@code onerror} property.
* @param onerror the value of the window's {@code onerror} property
*/
@JsxSetter
public void setOnerror(final Object onerror) {
setHandlerForJavaScript(Event.TYPE_ERROR, onerror);
}
/**
* Returns the value of the window's {@code onmessage} property.
* @return the value of the window's {@code onmessage} property
*/
@JsxGetter
public Object getOnmessage() {
return getEventHandler(Event.TYPE_MESSAGE);
}
/**
* Sets the value of the window's {@code onmessage} property.
* @param onmessage the value of the window's {@code onmessage} property
*/
@JsxSetter
public void setOnmessage(final Object onmessage) {
setHandlerForJavaScript(Event.TYPE_MESSAGE, onmessage);
}
/**
* Triggers the {@code onerror} handler, if one has been set.
* @param e the error that needs to be reported
*/
public void triggerOnError(final ScriptException e) {
final Object o = getOnerror();
if (o instanceof Function) {
final Function f = (Function) o;
String msg = e.getMessage();
final String url = e.getPage().getUrl().toExternalForm();
final int line = e.getFailingLineNumber();
final int column = e.getFailingColumnNumber();
Object jsError = e.getMessage();
if (e.getCause() instanceof JavaScriptException) {
msg = "uncaught exception: " + e.getCause().getMessage();
jsError = ((JavaScriptException) e.getCause()).getValue();
}
else if (e.getCause() instanceof EcmaError) {
msg = "uncaught " + e.getCause().getMessage();
final EcmaError ecmaError = (EcmaError) e.getCause();
final Scriptable err = Context.getCurrentContext().newObject(this, "Error");
ScriptableObject.putProperty(err, "message", ecmaError.getMessage());
ScriptableObject.putProperty(err, "fileName", ecmaError.sourceName());
ScriptableObject.putProperty(err, "lineNumber", Integer.valueOf(ecmaError.lineNumber()));
jsError = err;
}
final Object[] args = {msg, url, Integer.valueOf(line), Integer.valueOf(column), jsError};
f.call(Context.getCurrentContext(), this, this, args);
}
}
private void setHandlerForJavaScript(final String eventName, final Object handler) {
getEventListenersContainer().setEventHandler(eventName, handler);
}
/**
* {@inheritDoc}
*/
@Override
public Object call(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args) {
throw Context.reportRuntimeError("Window is not a function.");
}
/**
* {@inheritDoc}
*/
@Override
public Scriptable construct(final Context cx, final Scriptable scope, final Object[] args) {
throw Context.reportRuntimeError("Window is not a function.");
}
/**
* To be called when the property detection fails in normal scenarios.
*
* @param name the name
* @return the found object, or {@link Scriptable#NOT_FOUND}
*/
public Object getWithFallback(final String name) {
Object result = NOT_FOUND;
final DomNode domNode = getDomNodeOrNull();
if (domNode != null) {
// May be attempting to retrieve a frame by name.
final HtmlPage page = (HtmlPage) domNode.getPage();
result = getFrameWindowByName(page, name);
if (result == NOT_FOUND) {
result = getElementsByName(page, name);
if (result == NOT_FOUND) {
// May be attempting to retrieve element by ID (try map-backed operation again instead of XPath).
try {
final HtmlElement htmlElement = page.getHtmlElementById(name);
if (getBrowserVersion().hasFeature(JS_WINDOW_FRAME_BY_ID_RETURNS_WINDOW)
&& htmlElement instanceof HtmlFrame) {
final HtmlFrame frame = (HtmlFrame) htmlElement;
result = getScriptableFor(frame.getEnclosedWindow());
}
else {
result = getScriptableFor(htmlElement);
}
}
catch (final ElementNotFoundException e) {
result = NOT_FOUND;
}
}
}
if (result instanceof Window) {
final WebWindow webWindow = ((Window) result).getWebWindow();
result = getProxy(webWindow);
}
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public Object get(final int index, final Scriptable start) {
if (index < 0 || getWebWindow() == null) {
return Undefined.instance;
}
final HTMLCollection frames = getFrames();
if (frames == null || index >= frames.getLength()) {
return Undefined.instance;
}
return frames.item(Integer.valueOf(index));
}
private static Object getFrameWindowByName(final HtmlPage page, final String name) {
try {
return page.getFrameByName(name).getScriptableObject();
}
catch (final ElementNotFoundException e) {
return NOT_FOUND;
}
}
private Object getElementsByName(final HtmlPage page, final String name) {
// May be attempting to retrieve element(s) by name. IMPORTANT: We're using map-backed operations
// like getHtmlElementsByName() and getHtmlElementById() as much as possible, so as to avoid XPath
// overhead. We only use an XPath-based operation when we have to (where there is more than one
// matching element). This optimization appears to improve performance in certain situations by ~15%
// vs using XPath-based operations throughout.
final List elements = page.getElementsByName(name);
final boolean includeFormFields = getBrowserVersion().hasFeature(JS_WINDOW_FORMFIELDS_ACCESSIBLE_BY_NAME);
final Filter filter = new Filter(includeFormFields);
elements.removeIf(domElement -> !filter.matches(domElement));
if (elements.isEmpty()) {
return NOT_FOUND;
}
if (elements.size() == 1) {
return getScriptableFor(elements.get(0));
}
// Null must be changed to '' for proper collection initialization.
final String expElementName = "null".equals(name) ? "" : name;
return new HTMLCollection(page, true) {
@Override
protected List computeElements() {
final List expElements = page.getElementsByName(expElementName);
final List result = new ArrayList<>(expElements.size());
for (final DomElement domElement : expElements) {
if (filter.matches(domElement)) {
result.add(domElement);
}
}
return result;
}
@Override
protected EffectOnCache getEffectOnCache(final HtmlAttributeChangeEvent event) {
if ("name".equals(event.getName())) {
return EffectOnCache.RESET;
}
return EffectOnCache.NONE;
}
};
}
/**
* Returns the proxy for the specified window.
* @param w the window whose proxy is to be returned
* @return the proxy for the specified window
*/
public static WindowProxy getProxy(final WebWindow w) {
return ((Window) w.getScriptableObject()).windowProxy_;
}
/**
* Returns the text from the status line.
* @return the status line text
*/
@JsxGetter
public String getStatus() {
return status_;
}
/**
* Sets the text from the status line.
* @param message the status line text
*/
@JsxSetter
public void setStatus(final String message) {
status_ = message;
final StatusHandler statusHandler = webWindow_.getWebClient().getStatusHandler();
if (statusHandler != null) {
statusHandler.statusMessageChanged(webWindow_.getEnclosedPage(), message);
}
}
/**
* Returns the {@code innerWidth}.
* @return the {@code innerWidth}
* @see Mozilla doc
*/
@JsxGetter
public int getInnerWidth() {
return getWebWindow().getInnerWidth();
}
/**
* Sets the {@code innerWidth}.
* @param width the {@code innerWidth}
*/
@JsxSetter
public void setInnerWidth(final int width) {
getWebWindow().setInnerWidth(width);
}
/**
* Returns the {@code outerWidth}.
* @return the {@code outerWidth}
* @see Mozilla doc
*/
@JsxGetter
public int getOuterWidth() {
return getWebWindow().getOuterWidth();
}
/**
* Sets the {@code outerWidth}.
* @param width the {@code outerWidth}
*/
@JsxSetter
public void setOuterWidth(final int width) {
getWebWindow().setOuterWidth(width);
}
/**
* Returns the {@code innerHeight}.
* @return the {@code innerHeight}
* @see Mozilla doc
*/
@JsxGetter
public int getInnerHeight() {
return getWebWindow().getInnerHeight();
}
/**
* Sets the {@code innerHeight}.
* @param height the {@code innerHeight}
*/
@JsxSetter
public void setInnerHeight(final int height) {
getWebWindow().setInnerHeight(height);
}
/**
* Returns the {@code outerHeight}.
* @return the {@code outerHeight}
* @see Mozilla doc
*/
@JsxGetter
public int getOuterHeight() {
return getWebWindow().getOuterHeight();
}
/**
* Sets the {@code outerHeight}.
* @param height the {@code outerHeight}
*/
@JsxSetter
public void setOuterHeight(final int height) {
getWebWindow().setOuterHeight(height);
}
/**
* Prints the current page. The current implementation does nothing.
* @see
* Mozilla documentation
* @see MSDN documentation
*/
@JsxFunction
public void print() {
if (LOG.isDebugEnabled()) {
LOG.debug("window.print() not implemented");
}
}
/**
* Does nothing special anymore.
* @param type the type of events to capture
* @see HTMLDocument#captureEvents(String)
*/
@JsxFunction
public void captureEvents(final String type) {
// Empty.
}
/**
* Does nothing special anymore.
* @param type the type of events to capture
* @see HTMLDocument#releaseEvents(String)
*/
@JsxFunction
public void releaseEvents(final String type) {
// Empty.
}
/**
* An undocumented IE function.
*/
@JsxFunction(value = IE, functionName = "CollectGarbage")
public void collectGarbage() {
// Empty.
}
/**
* Returns computed style of the element. Computed style represents the final computed values
* of all CSS properties for the element. This method's return value is of the same type as
* that of element.style, but the value returned by this method is read-only.
*
* @param element the element
* @param pseudoElement a string specifying the pseudo-element to match (may be {@code null});
* e.g. ':before'
* @return the computed style
*/
@JsxFunction
public CSS2Properties getComputedStyle(final Object element, final String pseudoElement) {
if (!(element instanceof Element)) {
throw ScriptRuntime.typeError("parameter 1 is not of type 'Element'");
}
final Element e = (Element) element;
return getWebWindow().getComputedStyle(e.getDomNodeOrDie(), pseudoElement);
}
/**
* Returns the current selection.
* @return the current selection
*/
@JsxFunction
public Selection getSelection() {
final WebWindow webWindow = getWebWindow();
// return null if the window is in a frame that is not displayed
if (webWindow instanceof FrameWindow) {
final FrameWindow frameWindow = (FrameWindow) webWindow;
if (getBrowserVersion().hasFeature(JS_WINDOW_SELECTION_NULL_IF_INVISIBLE)
&& !frameWindow.getFrameElement().isDisplayed()) {
return null;
}
}
return getSelectionImpl();
}
/**
* Returns the current selection.
* @return the current selection
*/
public Selection getSelectionImpl() {
if (selection_ == null) {
selection_ = new Selection();
selection_.setParentScope(this);
selection_.setPrototype(getPrototype(selection_.getClass()));
}
return selection_;
}
/**
* Creates a modal dialog box that displays the specified HTML document.
* @param url the URL of the document to load and display
* @param arguments object to be made available via window.dialogArguments in the dialog window
* @param features string that specifies the window ornaments for the dialog window
* @return the value of the {@code returnValue} property as set by the modal dialog's window
* @see MSDN Documentation
* @see Mozilla Documentation
*/
@JsxFunction(IE)
public Object showModalDialog(final String url, final Object arguments, final String features) {
final WebWindow webWindow = getWebWindow();
final WebClient client = webWindow.getWebClient();
try {
final URL completeUrl = ((HtmlPage) getDomNodeOrDie()).getFullyQualifiedUrl(url);
final DialogWindow dialog = client.openDialogWindow(completeUrl, webWindow, arguments);
// TODO: Theoretically, we shouldn't return until the dialog window has been close()'ed...
// But we have to return so that the window can be close()'ed...
// Maybe we can use Rhino's continuation support to save state and restart when
// the dialog window is close()'ed? Would only work in interpreted mode, though.
final ScriptableObject jsDialog = dialog.getScriptableObject();
return jsDialog.get("returnValue", jsDialog);
}
catch (final IOException e) {
throw Context.throwAsScriptRuntimeEx(e);
}
}
/**
* Creates a modeless dialog box that displays the specified HTML document.
* @param url the URL of the document to load and display
* @param arguments object to be made available via window.dialogArguments in the dialog window
* @param features string that specifies the window ornaments for the dialog window
* @return a reference to the new window object created for the modeless dialog
* @see MSDN Documentation
*/
@JsxFunction(IE)
public Object showModelessDialog(final String url, final Object arguments, final String features) {
final WebWindow webWindow = getWebWindow();
final WebClient client = webWindow.getWebClient();
try {
final URL completeUrl = ((HtmlPage) getDomNodeOrDie()).getFullyQualifiedUrl(url);
final DialogWindow dialog = client.openDialogWindow(completeUrl, webWindow, arguments);
return dialog.getScriptableObject();
}
catch (final IOException e) {
throw Context.throwAsScriptRuntimeEx(e);
}
}
/**
* Gets the {@code controllers}. The result doesn't currently matter but it is important to return an
* object as some JavaScript libraries check it.
* @see Mozilla documentation
* @return some object
*/
@JsxGetter({FF, FF_ESR})
public Object getControllers() {
return controllers_;
}
/**
* Sets the {@code controllers}.
* @param value the new value
*/
@JsxSetter({FF, FF_ESR})
public void setControllers(final Object value) {
controllers_ = value;
}
/**
* Returns the value of {@code mozInnerScreenX} property.
* @return the value of {@code mozInnerScreenX} property
*/
@JsxGetter({FF, FF_ESR})
public int getMozInnerScreenX() {
return 10;
}
/**
* Returns the value of {@code mozInnerScreenY} property.
* @return the value of {@code mozInnerScreenY} property
*/
@JsxGetter({FF, FF_ESR})
public int getMozInnerScreenY() {
return 89;
}
private static final class Filter {
private final boolean includeFormFields_;
Filter(final boolean includeFormFields) {
includeFormFields_ = includeFormFields;
}
boolean matches(final Object object) {
if (object instanceof HtmlEmbed
|| object instanceof HtmlForm
|| object instanceof HtmlImage
|| object instanceof HtmlObject) {
return true;
}
return includeFormFields_
&& (object instanceof HtmlAnchor
|| object instanceof HtmlButton
|| object instanceof HtmlInput
|| object instanceof HtmlMap
|| object instanceof HtmlSelect
|| object instanceof HtmlTextArea);
}
}
/**
* Gets the name of the scripting engine.
* @see MSDN doc
* @return "JScript"
*/
@JsxFunction(value = IE, functionName = "ScriptEngine")
public String scriptEngine() {
return "JScript";
}
/**
* Gets the build version of the scripting engine.
* @see MSDN doc
* @return the build version
*/
@JsxFunction(value = IE, functionName = "ScriptEngineBuildVersion")
public int scriptEngineBuildVersion() {
return 12_345;
}
/**
* Gets the major version of the scripting engine.
* @see MSDN doc
* @return the major version
*/
@JsxFunction(value = IE, functionName = "ScriptEngineMajorVersion")
public int scriptEngineMajorVersion() {
return getBrowserVersion().getBrowserVersionNumeric();
}
/**
* Gets the minor version of the scripting engine.
* @see MSDN doc
* @return the minor version
*/
@JsxFunction(value = IE, functionName = "ScriptEngineMinorVersion")
public int scriptEngineMinorVersion() {
return 0;
}
/**
* Should implement the stop() function on the window object.
* (currently empty implementation)
* @see window.stop
*/
@JsxFunction({CHROME, EDGE, FF, FF_ESR})
public void stop() {
//empty
}
/**
* Returns the value of {@code pageXOffset} property.
* @return the value of {@code pageXOffset} property
*/
@JsxGetter
public int getPageXOffset() {
return 0;
}
/**
* Returns the value of {@code pageYOffset} property.
* @return the value of {@code pageYOffset} property
*/
@JsxGetter
public int getPageYOffset() {
return 0;
}
/**
* Returns the value of {@code scrollX} property.
* @return the value of {@code scrollX} property
*/
@JsxGetter({CHROME, EDGE, FF, FF_ESR})
public int getScrollX() {
return 0;
}
/**
* Returns the value of {@code scrollY} property.
* @return the value of {@code scrollY} property
*/
@JsxGetter({CHROME, EDGE, FF, FF_ESR})
public int getScrollY() {
return 0;
}
/**
* Returns the value of {@code netscape} property.
* @return the value of {@code netscape} property
*/
@JsxGetter({FF, FF_ESR})
public Netscape getNetscape() {
return new Netscape(this);
}
/**
* {@inheritDoc}
* Used to allow re-declaration of constants (eg: "var undefined;").
*/
@Override
public boolean isConst(final String name) {
if ("undefined".equals(name) || "Infinity".equals(name) || "NaN".equals(name)) {
return false;
}
return super.isConst(name);
}
/**
* {@inheritDoc}
*/
@Override
public boolean dispatchEvent(final Event event) {
event.setTarget(this);
final ScriptResult result = fireEvent(event);
return !event.isAborted(result);
}
/**
* Getter for the {@code onchange} event handler.
* @return the handler
*/
@JsxGetter
public Object getOnchange() {
return getEventHandler(Event.TYPE_CHANGE);
}
/**
* Setter for the {@code onchange} event handler.
* @param onchange the handler
*/
@JsxSetter
public void setOnchange(final Object onchange) {
setHandlerForJavaScript(Event.TYPE_CHANGE, onchange);
}
/**
* Getter for the {@code onsubmit} event handler.
* @return the handler
*/
@JsxGetter
public Object getOnsubmit() {
return getEventHandler(Event.TYPE_SUBMIT);
}
/**
* Setter for the {@code onsubmit} event handler.
* @param onsubmit the handler
*/
@JsxSetter
public void setOnsubmit(final Object onsubmit) {
setHandlerForJavaScript(Event.TYPE_SUBMIT, onsubmit);
}
/**
* Posts a message.
* @param message the object passed to the window
* @param targetOrigin the origin this window must be for the event to be dispatched
* @param transfer an optional sequence of Transferable objects
* @see MDN documentation
*/
@JsxFunction
public void postMessage(final String message, final String targetOrigin, final Object transfer) {
final WebWindow webWindow = getWebWindow();
final Page page = webWindow.getEnclosedPage();
final URL currentURL = page.getUrl();
if (!"*".equals(targetOrigin) && !"/".equals(targetOrigin)) {
final URL targetURL;
try {
targetURL = new URL(targetOrigin);
}
catch (final Exception e) {
throw Context.throwAsScriptRuntimeEx(
new Exception(
"SyntaxError: Failed to execute 'postMessage' on 'Window': Invalid target origin '"
+ targetOrigin + "' was specified (reason: " + e.getMessage() + "."));
}
if (getPort(targetURL) != getPort(currentURL)) {
return;
}
if (!targetURL.getHost().equals(currentURL.getHost())) {
return;
}
if (!targetURL.getProtocol().equals(currentURL.getProtocol())) {
return;
}
}
final MessageEvent event = new MessageEvent();
final String origin = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();
event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin, "", this, transfer);
event.setParentScope(this);
event.setPrototype(getPrototype(event.getClass()));
final JavaScriptEngine jsEngine = (JavaScriptEngine) webWindow.getWebClient().getJavaScriptEngine();
final PostponedAction action = new PostponedAction(page, "Window.postMessage") {
@Override
public void execute() throws Exception {
final ContextAction
© 2015 - 2024 Weber Informatics LLC | Privacy Policy