XQuery in the Browser
Ghislain Fourny Markus Pilman Daniela Florescu Systems Group Systems Group Oracle ETH Zürich, Switzerland ETH Zürich, Switzerland Redwood City, CA, USA [email protected] [email protected] dana.fl[email protected] Donald Kossmann Tim Kraska Darin McBeath Systems Group Systems Group Elsevier ETH Zürich, Switzerland ETH Zürich, Switzerland West Chester, OH, USA [email protected] [email protected] [email protected]
ABSTRACT 1. INTRODUCTION Since the invention of the Web, the browser has become Over the years, the code producing Web pages has kept more and more powerful. By now, it is a programming and moving back and forth between the client and the server. execution environment in itself. The predominant language Many applications are server-side, many others are client- to program applications in the browser today is JavaScript. side, and the borders are blurred. After a period in which With browsers becoming more powerful, JavaScript has been almost all the code was on the server (thin-clients), we are extended and new layers have been added (e.g., DOM-Sup- now experiencing the AJAX and Web 2.0 trend, in which a port and XPath). Today, JavaScript is very successful and great deal of code is executed on the client again. Client- applications and GUI features implemented in the browser side software today means browser-embedded software, so have become increasingly complex. The purpose of this pa- that there is no installation. The browser is no longer just per is to improve the programmability of Web browsers by a rendering engine, it has become a programming platform, enabling the execution of XQuery programs in the browser. more powerful than ever. Although it has the potential to ideally replace JavaScript, The most popular programming language for the browser it is possible to run it in addition to JavaScript for more flex- today is JavaScript. JavaScript was specifically designed to ibility. Furthermore, it allows instant code migration from run in a Web browser and, thus, JavaScript is a good match the server to the client and vice-versa. This enables a signif- for the development of client-side programs. In particu- icant simplification of the technology stack. The intuition lar, JavaScript is well-suited for programming event-based is that programming the browser involves mostly XML (i.e., user interfaces in the Web browser. All main-stream Web DOM) navigation and manipulation, and the XQuery family browsers today support the execution of JavaScript natively. of W3C standards were designed exactly for that purpose. In addition to JavaScript, there are several alternatives to The paper proposes extensions to XQuery for Web browsers effect browser-embedded application programming. First, and gives a number of examples that demonstrate the use- JavaScript has been extended in order to embed XPath fulness of XQuery for the development of AJAX-style appli- code into a JavaScript program. XPath is useful in order cations. Furthermore, the paper presents the design of an to declaratively navigate the DOM that represents the Web XQuery plug-in for Microsoft’s Internet Explorer. The pa- page. Second, the Google Web Toolkit (GWT) is a popular per also gives examples of applications which were developed tool that allows cross-compilation from Java to JavaScript. with the help of this plug-in. GWT helps Java programmers to get started with program- ming the Web browser without the need to learn a new pro- gramming language. Furthermore, GWT enables the devel- Categories and Subject Descriptors opment of both server-side and client-side application code D.3.2 [Software Engineering]: Language Classifications— in a uniform way. Another extension provided by Google is XQuery; H.4.0 [Information Systems Applications]: Ge- the Gears framework which, among others, supports persis- neral tent data (i.e., database access with SQL) and threading as part of JavaScript programs. Finally, Adobe Flash and Flex are popular ways to program powerful user interfaces in the General Terms Web browser. Design, Languages, Performance, Standardization The purpose of this paper is to provide another alternative to program applications inside the Web browser: XQuery. Keywords The goal is to combine the advantages of the existing alter- natives (e.g., JavaScript, XPath, GWT, and Gears) into a XML, XQuery, browser, script, scripting, JavaScript, DOM, single, uniform, and powerful offering. Because it is Turing- HTML, XHTML, events, stylesheets, CSS, client-side pro- complete, XQuery is powerful enough to implement any- gramming, mash-up thing that can be implemented by JavaScript or GWT. How- Copyright is held by the International World Wide Web Conference Com- ever, XQuery can also co-exist with existing technologies in mittee (IW3C2). Distribution of these papers is limited to classroom use, the Web browser, thereby re-using existing JavaScript and and personal use by others. Flex application code and using XQuery to implement func- WWW 2009, April 20–24, 2009, Madrid, Spain. ACM 978-1-60558-487-4/09/04. tionality that is not well supported by the existing tech- power of XQuery and the plug-in are available at http: nologies. This also provides a graceful evolution of existing //www.xqib.org. systems and to compensate for features that are not well • Show that building an XQuery-on-all-tiers application supported by XQuery today. from scratch significantly simplifies the technology stack. XQuery has several compelling reasons why it should be The remainder of this paper is organised as follows: Sec- used in the browser. First, XQuery is a super-set of XPath tion 2 describes the state of the art and gives the main fea- which is already heavily used inside Web browsers in order tures of JavaScript, XPath embedded in JavaScript, GWT, to navigate the DOM. XQuery is not only useful to navigate Gears, and Flex. The goal of our work is to combine these the DOM; it can also manipulate the DOM in a declarative features into a more powerful programming framework based way, it supports declarative access to persistent data (like on XQuery. Section 3 gives a brief overview of the XQuery SQL in Gears), it has a powerful function and operator li- family. Section 4 shows the proposed extensions for XQuery brary (e.g., for dates and times), and it supports scripting so that it becomes a candidate for Web browser-embedded (like JavaScript). In a nutshell, XQuery was designed to programming. Section 5 gives the design of an XQuery plug- process and correlate data on the Web and that is exactly in for the Internet Explorer. Section 6 describes our expe- what AJAX-style programs and Web mash-ups need to do. rience in using this plug-in for two example applications as Section 6 gives an example application that show-cases this well as notes on XQuery-only web applications. Section 7 property. Furthermore, XQuery is carefully designed to be contains conclusions and shows avenues for future research. highly optimisable. Second, XQuery runs on all application tiers (database, 2. STATE OF THE ART middleware, and Web browser) and is thus highly portable. Given the growing importance of the Web browser, a num- For instance, all major database vendors (e.g., IBM, Mi- ber of alternative techniques to develop Web browser-based crosoft, and Oracle) have implemented XQuery as part of applications have been developed. This section gives an their database product and many middleware products (e.g., overview of the most prominent languages and tools: Java- BEA’s workflow engine, information integration product, Script, XPath embedded into JavaScript, GWT, Gears, and and enterprise service bus) support XQuery. Hence, XQuery Flex. The goal of this work is to combine the advantages of code can be shipped between different tiers which can be these languages and tools into an XQuery application devel- exploited in order to reduce cost. Section 6 presents an ex- opment framework. ample application that show-cases this advantage. Third, XQuery is a family of standards endorsed by the 2.1 JavaScript W3C so that it is standardised and the whole XQuery familiy JavaScript was developed in 1995. The initial motivation interoperates well with other W3C recommendations; e.g., was to validate forms at the client-side without the need to XML, XML Schema, REST/Web Services. The XQuery exchange data with the server (which was much slower than family is a complete and powerful programming model. today). Today, JavaScript has become a popular language Finally, there is a significant industry push for XQuery. A and several extensions have been added by vendors to make great deal of tools are developed and products are maturing. it a powerful programming tool for the Web browser. AJAX XQuery is taught in the curricula of the Computer Science (Asynchronous JavaScript And XML) is probably the best programs of many universities. As a consequence, it can example of how JavaScript can help build powerful client- be expected that more and more XQuery programmers will side applications. JavaScript is a great programming lan- soon appear on the job market. guage for the browser because JavaScript was specifically Again, the goal of this work is to study XQuery as an al- designed for this purpose. ternative and complementary technology in order to imple- An important feature of JavaScript is that it supports ment client-side applications inside the Web browser. That event-based programming which is needed for modern user is, the purpose is to study the potential of this technology interfaces. A second feature of JavaScript is that it supports and see, with the help of examples, how it co-exists with ex- DOM, which is the API used in order to navigate and ma- isting technology such as JavaScript. To this end, this paper nipulate Web pages in a Web browser. A third feature of reports on the following contributions: JavaScript is its availability in all browsers. • Show that XQuery is a viable option for client-side, XQuery naturally supports the navigation and manipula- browser-embedded applications. We present examples which tion of Web pages because XQuery supports the navigation show the advantages and expressive power of XQuery for this and manipulation of XML and, thus, any kind of data stored purpose. behind a DOM API. The support for event-based program- • Extend XQuery for the browser, thereby providing a ming in XQuery will be detailed in Section 4. As a result, syntax for event-based programming, CSS, and access to XQuery is a viable candidate to replace JavaScript. As will the Browser Object Model. become clear in the remainder of this paper, however, both • Design a plug-in for running XQuery in the Web browser. XQuery and JavaScript can also co-exist in a single applica- A first release of this plug-in for Microsoft’s Internet Ex- tion. plorer is available for free download and open sourced at http://www.xqib.org. An implementation of the plug-in 2.2 Embedded XPath in JavaScript for Firefox is currently on the way and should be ready in Since it is quite cumbersome to navigate Web pages using 2009. DOM, Web browsers have supported XPath for a long time. • Give two application examples, a Web mashup and a In particular, it is possible to embed XPath expressions into publishing application, which demonstrate the flexibility of JavaScript programs. Many browsers support this feature. XQuery to integrate horizontally and vertically into an ap- The following example demonstrates this feature for Firefox: plication stack. Additional examples that demonstrate the var allDivs, newElement; allDivs = document.evaluate( In order to run ActiveScript, a Web browser must install "//div[contains(., ’love’)]", a Flex plug-in, in the same way as proposed in this work document, null, XPathResult. for running XQuery in a Web browser. Like JavaScript, UNORDERED_NODE_SNAPSHOT_TYPE, null); ActiveScript and XQuery can co-exist in the Web browser - if (allDivs.snapshotLength > 0) { in fact, all three programming languages can be embedded newElement = document.createElement(’img’); into a Web page. This way, it is possible to design fancy user newElement.src = ’http://.../heart.gif’; interfaces with Flex and program more advanced application document.body.insertBefore(newElement, logic and Web page manipulation with, say, XQuery. Such document.body.firstChild); an approach has been taken already in several projects at } ETH Zurich. This JavaScript code uses XPath as part of the document. evaluate function. This JavaScript function is called with 3. XQUERY OVERVIEW an XPath expression which looks for all divs containing the This section gives an overview of XQuery, the XQuery word ”love”. If such an occurence is found, an image with a Update Facility, the XQuery Scripting Facility as well as heart (i.e., “heart.gif”) is inserted into the Web page. Web services and REST support in XQuery. At the end of Obviously, XQuery naturally supports navigation of Web this section, we explain why XQuery is suitable for browser- pages with XPath because XPath is a sub-set of the XQuery embedded programming and enables the implementation of programming language. That is, all XPath expressions can whole applications in a single programming language, there- be executed by an XQuery processor. by simplifying the technology stack of modern Web-based 2.3 Google Web Tools (GWT) applications. As mentioned in the introduction, GWT enables Java pro- 3.1 XQuery grammers to implement client-side applications which run in XQuery is a shorthand for XML Query Language. It has the Web browser. With GWT, programmers can program in been a W3C recommendation since January 2007 [4]. Orig- Java and compile their code to an AJAX application. Hence, inally, it was designed as a query language to query and programmers no longer need to worry about browser incom- transform XML data natively. By now, it has evolved to a patibilities, and a lot of JavaScript inconveniences such as general purpose programming language that can read, up- errors (type mismatch, etc) are caught by the compiler at date, and transform any kind of data (including, of course, compile-time instead of been caught at runtime. Further- XML). XQuery is a functional programming language, and more, GWT programmers can be supported by the same it is Turing complete. IDE tools as regular Java programmers, e.g. Eclipse. XQuery is a super-set of XPath. That is, any valid XPath One big advantage of GWT is that GWT blurs the dis- expression is also a valid XQuery expression. Hence, there is tinction between the presentation layer and the“middle-tier” no need to embed XPath into XQuery in the way it is done of an application: in principle, GWT enables the movement for JavaScript. Like XPath 2.0, XQuery uses an extended of code between these two tiers in both directions based on XML Data Model [7]: The XQuery 1.0 and XPath 2.0 Data technology trends. As described in Section 6, this is an im- Model. XQuery is strongly typed, yet flexible because data portant feature. Our work on an XQuery plug-in facilitates can be typed as “untyped”. In particular, XQuery can na- the same feature because XQuery also runs in the middle-tier tively process (untyped) Web pages. and (with the help of the plug-in) in the presentation layer. XQuery has a broad functionality, covering simple ex- In fact, XQuery runs on all three application tiers (including pressions such as constants, variables, and comparisons to the database), facilitating even more code movement. complex expressions for database queries, transformations, and information retrieval. For example, the FLWOR (pro- 2.4 Gears nounced “flower”) expression corresponds to the “SELECT Gears is an offering from Google in order to enable the de- FROM WHERE” statement in SQL, for example: velopment of full-fledged applications inside the Web browser. For instance, Google Apps (i.e., Google’s competition to Mi- for $x at $i in crosoft’s Office products) were developed with the help of doc("bill.xml")/paymentorder/paymentorders Gears. Among the features provided by Gears are support let $price := $x/price for databases inside the browser. With the help of this fea- where $x/name ftcontains "computer" ture, browser-based applications can run even if the client is return
not connected to the Internet. Furthermore, such a client- {$x/name} side database improves performance if fine-grained changes {data($price)} are made, e.g., to a text document. Again, our work on enabling XQuery in Web browsers In order to support information retrieval, XQuery also targets in exactly the same direction as Gears. XQuery can involves full-text search [3] as shown below. also be used to facilitate client-side database access. Fur- for $b in /books/book thermore, our XQuery plug-in naturally co-exists with the where $b/title ftcontains Gears browser extensions. ("dog" with stemming) ftand "cat" 2.5 Flex return $b/author Flex is a popular tool in order to develop graphical user This example finds all authors of all books the title of interfaces for Web browsers. It is based on a programming which contains the word “cat”, as well as the word “dog” or language called ActiveScript which is similar to JavaScript. a word with the same stem. Just like any other functional programming language, an set $b := //book[title="starwars"]; XQuery expression is evaluated in a context. The context insert node $b into doc("lib.xml")/books; contains functions, namespaces, schemas, and variable bind- set $b := doc("lib.xml")//book[title="starwars"]; ings. For instance, the expression $x will be evaluated using insert node
6 movies into $b; } the context; if the variable $x is not defined in the con- This program is a block, the expressions of which are exe- text, then an error is raised as part of the evaluation of cuted sequentially. First, a variable $b is declared. $b is ini- this expression. Otherwise, this expression is evaluated to tialized to a book which is copied and inserted into lib.xml. the value of $x as defined in the context. Likewise, func- Then $b is set to the newly inserted node in lib.xml (it can tion invocations are evaluated according to the definition of be read because this instruction sees the side effect of the the functions in the context. The XQuery recommendation insertion). Finally, a comment is inserted into the book. already defines the “http://www.w3c.org/xquery-functions” The XQuery Scripting Extension is still in its early stages namespace and a whole function library in this namespace of standardisation but first implementations already exist. (e.g., sum, distinct-values, etc.) [9]. Extending the context with new browser-specific namespace, schema, and function 3.4 REST and Web Services Support definitions is an important part of integrating XQuery into The W3C is also currently standardising extensions to the Web browser (Section 4.1). XQuery in order to effect REST and Web Service calls and 3.2 XQuery Update Facility in order to make sure that XQuery modules and functions can be called directly with the help of REST or Web Ser- XQuery 1.0 is side-effect free, i.e., an XQuery expres- vice calls. With the current proposal discussed inside the sion cannot alter an XML node. Obviously, side effects W3C working group, for instance, a Web service could be are needed for AJAX-style programming in order to change defined using the following XQuery code (i.e., a Web service the Web page based on the actions of a user. The XQuery corresponds to an XQuery module): Update Facility [6] has been designed to extend XQuery in order to facilitate updates to XML nodes. For instance, module namespace ex="www.example.ch" port:2001; the XQuery Update Facility enables to insert new elements, declare option fn:webservice "true"; delete elements, rename elements and replace the content declare function ex:mul($a,$b) {$a * $b}; of an element. Since DOM is an API for XML data, the The following XQuery code could be used in order to call XQuery Update Facility can be used naturally in order to the Web service defined above: update Web pages; i.e., data stored behind a DOM inter- import module namespace ab="www.example.ch" face. The XQuery Update Facility has been a candidate at "http://localhost:2001/wsdl"; recommendation since August 2008. replace value of node The following contains two example updates, an insert of
html//input[@name="textbox"]/value a new book into a library and the update of the price of a with ab:mul(2,5) book: Support for REST, which seems to be more popular on the open Web, goes along the same lines. insert node
into doc("library.xml")/books, replace value of node 4. XQUERY IN THE BROWSER doc("bill.xml")/bill/items[@id="computer"]/price The previous section showed that XQuery has all the in- with 1500 gredients needed to develop Web-based applications. It pro- cesses XML data natively, it is declarative, yet powerful All modifications are performed once the expression is en- enough for complex applications, and it supports remote tirely evaluated: there are no side effects until the end and calls via REST and Web Services. This section presents ex- instructions do not see the side effects of former instructions. tensions to XQuery so that XQuery becomes a viable option 3.3 XQuery Scripting Extension for AJAX-style applications in the Web browser. Further- more, it shows how XQuery can be embedded into HTML The XQuery Scripting Extension [5] is an extension of pages for execution inside the Web browser. XQuery and the XQuery Update Facility. With this exten- sion, XQuery becomes a full-fledged programming language 4.1 Overview which can be used in order to program any kind of applica- Like JavaScript, we propose to embed XQuery scripts into tion. The main difference as compared to XQuery and the HTML documents with a tag. XQuery Update Facility is that updates become visible dur- XQuery expressions in the browser are executed in a brow- ing the execution of a program. That is, XQuery expressions ser-specific context. This context contains all the name- can be ordered for sequential execution and the effects of the spaces and function libraries (Section 3) as well as browser- execution of one expression (e.g., an assignment) become specific extensions such as the predefined functions. visible for the execution of other, sub-sequent expressions. The processing model is the following: XQuery (and Java- Furthermore, the XQuery Scripting Extensions introduces Script) code is executed at the beginning, thereby regis- several new expressions which are commonly found in mod- tering events according to the DOM level 3 standard [8]. ern programming languages; e.g., blocks, variable declara- Thus, the browser listens for these events and executes the tion and assignment, while loops, continue, break, returning XQuery functions (or JavaScript or VBScript code) accord- values as a result of executing a function. ingly. Currently, JavaScript is executed first, then XQuery The following gives a simple example program written us- (this is the way browsers do it because JavaScript is sup- ing the XQuery Scripting Extension: ported natively). There can be other models (e.g., execution { declare variable $b; in order of the tags) in the future. We will follow the tradition and provide the Hello World of window objects in JavaScript (status, name, location, ...). version of XQuery in the Browser. The same is true for location nodes (href, host, port, ...). In addition, the browser:self() function returns a window
Hello World Page node which is a descendant of the XML element above and In order to retrieve certain properties (e.g., a frame, a
location), it is possible to navigate through these elements Again, the XQuery code is embedded into a using XQuery. (Recall that XQuery is a superset of XPath.) tag of the HTML webpage. In the header, the script pops Furthermore, the window element can be manipulated using up a “Hello, World!” message. This code is called when the the XQuery Update Facility; thereby changing the browser’s page is loaded. window. The following lists some examples (the equivalent The examples in the next subsection show that XQuery JavaScript is listed as a comment, below). is as expressive as JavaScript; the main difference is that it This code looks for a child of the top window which is takes much less code to process and manipulate a webpage called “leftframe”: using XQuery than using JavaScript because XQuery was designed for that purpose. In the rest of this section, we browser:top()//window[@name="leftframe"] will also detail browser-specific extensions to XQuery. The (: JavaScript: top.frame["leftframe"] :) most critical ones are event handling and CSS handling. The following example changes the status of the current window to “Welcome”: 4.2 Browser Context replace value of node browser:self()/status As mentioned in Section 3.1, each XQuery expression is with "Welcome"; evaluated in a context. By default from the XQuery recom- (: JavaScript: self.status = "..." :) mendation, this context already comes with a rich function library [9]. Embedding XQuery into the browser, extends Here a new variable $win initialised to the second child of the context with one additional namespace (i.e., “http:// the current window is declared: www.example.com/browser” which is bound to the prefix declare variable $win := “browser”). Furthermore, the context includes browser-spe- browser:self()/frames/window[2]; cific functions. For instance, the browser:self() function re- (: JavaScript: var win = self.frames[2] :) turns all the information of the browser’s current window; To change the location of the variable $win (as above) and a call to this function is equivalent to accessing the win- cause a new webpage to be displayed, one can write: dow object in JavaScript. This way, browser-specific compo- nents can be accessed using XQuery just as using JavaScript. replace value of node $win/location/href The remainder of this subsection gives examples for some of with "http://www.dbis.ethz.ch" the pre-defined functions and types in the browser-specific (: JavaScript: win.location = "..." :) XQuery context. The following code raises an alert giving the date and time at which the variable $win bound above was last modified: 4.2.1 Window browser:alert($win/lastModified) Information about the window (or the frame within which (: JavaScript: alert(win.lastModified) :) the current document is shown) can be accessed with Java- Script through the window object. Retrieving the browser’s All these examples can be implemented easily in JavaScript window objects can be implemented in XQuery using the too, as shown in the comments below. But XQuery can do browser:top() function. The browser:top() function returns more. an XML element representing the topmost window (the equiv- This code looks for any frame (children, grandchildren... alent of top in JavaScript). It has the following form (for of top()) which is named ”myframe”: the sake of simplicity, we omit namespaces): browser:top()//window[@name="myframe"]
(the browser:document function is explained in 4.2.3). The last example requires significantly more JavaScript code to accomplish the same job. Note that this function call might return different results Like in JavaScript, there are security issues regarding nav- within the same query and is therefore marked as non-deter- igation through window nodes: a malicious Web site could ministic. A window node contains properties similar to those tamper with documents in other windows, or learn about the location of other windows. To avoid this, we suggest • Window-related functions: windowMoveBy, window- to implement window nodes using pull (as opposed to push) MoveTo, windowOpen, windowClose, alert, prompt, and to perform checks in the implementation of all accessors confirm in the window nodes and their descendants (e.g., accessors to get the value of a node, or its children) as well as in • History-related functions: historyBack, historyForward, routines which tamper with those nodes (when updates are historyGo applied). For example, this could be based on a same-origin policy like in JavaScript, or on any other suitable policy. If • Document-related functions (note that with XQuery, the check is not successful, an empty sequence is returned. best practice would be to modify the XDM and avoid Imagine, for example, that an application can get a refer- using those functions): write, writeln. ence to a window node at some point in time (e.g., the pages The programmer might also want to access browser infor- were on the same domain). If later the policy no longer al- mation and write browser-specific code in XQuery: lows its use (e.g., the user navigated to another domain), then this node becomes useless. That is, all accessors re- if (browser:navigator()/appName turn an empty sequence and thus, it is impossible to learn ftcontains "Mozilla") then anything about the new location of this window. browser:alert("You are running Mozilla") Also for security reasons, we propose to block the fn:doc else if (browser:navigator()/appName and fn:put functions in the browser. ftcontains "Internet Explorer") then browser:alert("You are running IE") 4.2.2 Screen and Navigator Two other important objects in JavaScript are the win- 4.3 Events dow.screen object and the window.navigator object which One of the most important features of client-side pro- give information on the screen (e.g., size, etc) and the navi- gramming is event-handling. The basic principle of event- gator (e.g., vendor, version, etc). handling is that some functions (called listeners) are called In XQuery, this information can be accessed with two when an event occurs at a certain location. For this call to functions browser:screen() and browser:navigator(). Both occur, the listener is registered in advance. return an XML node from two XML elements similar to In JavaScript, there are two ways to register for events. the one shown above (but much simpler). For example, the The first, simple way is to use e.g. the onclick, onload prop- name of the navigator is accessed with erties. The second way is to add listeners manually. browser:navigator()/appName In XQuery, a first approach could be to use a pre-defined (: JavaScript: navigator.appName :) function in the browser context which supports the regis- and the height of the screen with tration of listeners for events. Those functions would be browser:screen()/height high-order functions as they take functions as an argument. (: JavaScript: screen.height :) As registering events is a very important scheme, we suggest All of the properties available with the JavaScript screen a second approach: an extension of the XQuery syntax as and navigator objects are accessible as children of the nodes shown in the following subsection. returned by these functions in XQuery. 4.3.1 Managing event listeners in XQuery 4.2.3 The Document To demonstrate the mechanism, let us assume we have the Each Web page is a self-contained XML document. If one following function which we would like to be called when the possesses a window node, say, stored in $w, it is possible to user clicks on a button. get the corresponding document by calling browser:document declare sequential function local:myEventListener ($w). ($evt, $obj) as xs:boolean { The document in browser:self() deserves a special treat- declare variable $message =
; and straightforward with XQuery. exit with browser:alert(data($message)); Similarly to window nodes, for security reasons, a check is }; performed when the browser:document() function is called. If it fails, an empty sequence is returned. This very simple function raises a message box with infor- For example, an application could access all HTML div el- mation on the event (this is the information which is passed ements in the document containing the XQuery script with: as parameters: the event itself, and its location). //div We would like to register this function as a listener for a and all images in a children window with click event at the button named “button”. browser:document(browser:self()/frames/*[2])//img In JavaScript, we register such a listener with: document.getElementById("button").addEventListener 4.2.4 The browser functions ("onclick", myEventListener, false) There are some further browser built-in functions avail- able in the browser namespace. We list some of them here. For XQuery, we propose the following syntax for register- We omit comments as the names are self-explanatory and ing an event: the names are similar to equivalent JavaScript functions. on event "onclick" at //input[@id="button"] For more information, see [10], Chapter 5. attach listener local:myEventListener (This means that local:myEventListener shall be called at "http://www.example.com/wsdl"; whenever the user clicks at the location specified.) declare updating function For deregistering an event: local:showHint($str as xs:string) { on event "onclick" at //input[@id="button"] if(fn:length($str)) eq 0) detach listener local:myEventListener do replace value of //*[@id="txtHint"] with () (This means that we cancel the registration, i.e., the lis- else tener shall no longer be called if the events occurs.) on event "stateChanged" For triggering an event: behind ab:getHint($str) trigger event "onclick" at //input[@id="myButton"] attach listener my:onResult }; (This simulates a user clicking at the specified location.) declare updating function This corresponds to the following XQuery grammar ex- local:onResult($readyState, $result) { tension: if($readyState eq 4) then ExprSingle ::= (all existing options) do replace value of //*[@id="txtHint"] | EventAttach | EventDetach with $result | EventTrigger else () }; EventAttach ::= "on" "event" ExprSingle ("at"|"behind") ExprSingle