call_on_focused_field, modify_region: support richedit frames
[conkeror.git] / modules / utils.js
blob7fe13f9c78fa6319e1418dca9dabf0922353d1f8
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2010 John J. Foerch
4  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
5  *
6  * Use, modification, and distribution are subject to the terms specified in the
7  * COPYING file.
8 **/
10 in_module(null);
12 require("io");
14 function string_hashset () {}
15 string_hashset.prototype = {
16     constructor: string_hashset,
18     add: function (s) {
19         this["-" + s] = true;
20     },
22     contains: function (s) {
23         return (("-" + s) in this);
24     },
26     remove: function (s) {
27         delete this["-" + s];
28     },
30     for_each: function (f) {
31         for (var i in this) {
32             if (i[0] == "-")
33                 f(i.slice(1));
34         }
35     },
37     iterator: function () {
38         for (let k in this) {
39             if (i[0] == "-")
40                 yield i.slice(1);
41         }
42     }
45 function string_hashmap () {}
46 string_hashmap.prototype = {
47     constructor: string_hashmap,
49     put: function (s,value) {
50         this["-" + s] = value;
51     },
53     contains: function (s) {
54         return (("-" + s) in this);
55     },
57     get: function (s, default_value) {
58         if (this.contains(s))
59             return this["-" + s];
60         return default_value;
61     },
63     get_put_default: function (s, default_value) {
64         if (this.contains(s))
65             return this["-" + s];
66         return (this["-" + s] = default_value);
67     },
69     remove: function (s) {
70         delete this["-" + s];
71     },
73     for_each: function (f) {
74         for (var i in this) {
75             if (i[0] == "-")
76                 f(i.slice(1), this[i]);
77         }
78     },
80     for_each_value: function (f) {
81         for (var i in this) {
82             if (i[0] == "-")
83                 f(this[i]);
84         }
85     },
87     iterator: function (only_keys) {
88         if (only_keys) {
89             for (let k in Iterator(this, true)) {
90                 if (k[0] == "-")
91                     yield k.slice(1);
92             }
93         } else {
94             for (let [k,v] in Iterator(this, false)) {
95                 if (k[0] == "-")
96                     yield [k.slice(1),v];
97             }
98         }
99     }
103 // Put the string on the clipboard
104 function writeToClipboard (str) {
105     var gClipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"]
106         .getService(Ci.nsIClipboardHelper);
107     gClipboardHelper.copyString(str);
111 function makeURLAbsolute (base, url) {
112     // Construct nsIURL.
113     var ioService = Cc["@mozilla.org/network/io-service;1"]
114         .getService(Ci.nsIIOService);
115     var baseURI  = ioService.newURI(base, null, null);
116     return ioService.newURI(baseURI.resolve(url), null, null).spec;
120 function make_file (path) {
121     if (path instanceof Ci.nsILocalFile)
122         return path;
123     if (path == "~")
124         return get_home_directory();
125     var f;
126     if (path.substring(0,2) == "~/") {
127         f = get_home_directory();
128         f.appendRelativePath(path.substring(2));
129     } else {
130         f = Cc["@mozilla.org/file/local;1"]
131             .createInstance(Ci.nsILocalFile);
132         f.initWithPath(path);
133     }
134     return f;
138 function make_file_from_chrome (url) {
139     var crs = Cc['@mozilla.org/chrome/chrome-registry;1']
140         .getService(Ci.nsIChromeRegistry);
141     var file = crs.convertChromeURL(make_uri(url));
142     return make_file(file.path);
145 function get_document_content_disposition (document_o) {
146     var content_disposition = null;
147     try {
148         content_disposition = document_o.defaultView
149             .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
150             .getInterface(Components.interfaces.nsIDOMWindowUtils)
151             .getDocumentMetadata("content-disposition");
152     } catch (e) { }
153     return content_disposition;
157 function set_focus_no_scroll (window, element) {
158     window.document.commandDispatcher.suppressFocusScroll = true;
159     element.focus();
160     window.document.commandDispatcher.suppressFocusScroll = false;
163 function do_repeatedly_positive (func, n) {
164     var args = Array.prototype.slice.call(arguments, 2);
165     while (n-- > 0)
166         func.apply(null, args);
169 function do_repeatedly (func, n, positive_args, negative_args) {
170     if (n < 0)
171         do func.apply(null, negative_args); while (++n < 0);
172     else
173         while (n-- > 0) func.apply(null, positive_args);
178  * Given a node, returns its position relative to the document.
180  * @param node The node to get the position of.
181  * @return An object with properties "x" and "y" representing its offset from
182  *         the left and top of the document, respectively.
183  */
184 function abs_point (node) {
185     var orig = node;
186     var pt = {};
187     try {
188         pt.x = node.offsetLeft;
189         pt.y = node.offsetTop;
190         // find imagemap's coordinates
191         if (node.tagName == "AREA") {
192             var coords = node.getAttribute("coords").split(",");
193             pt.x += Number(coords[0]);
194             pt.y += Number(coords[1]);
195         }
197         node = node.offsetParent;
198         // Sometimes this fails, so just return what we got.
200         while (node.tagName != "BODY") {
201             pt.x += node.offsetLeft;
202             pt.y += node.offsetTop;
203             node = node.offsetParent;
204         }
205     } catch(e) {
206 //      node = orig;
207 //      while (node.tagName != "BODY") {
208 //          alert("okay: " + node + " " + node.tagName + " " + pt.x + " " + pt.y);
209 //          node = node.offsetParent;
210 //      }
211     }
212     return pt;
216 const XHTML_NS = "http://www.w3.org/1999/xhtml";
217 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
218 const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
219 const XLINK_NS = "http://www.w3.org/1999/xlink";
220 const SVG_NS = "http://www.w3.org/2000/svg";
222 function create_XUL (window, tag_name) {
223     return window.document.createElementNS(XUL_NS, tag_name);
227 /* Used in calls to XPath evaluate */
228 function xpath_lookup_namespace (prefix) {
229     return {
230         xhtml: XHTML_NS,
231         m: MATHML_NS,
232         xul: XUL_NS,
233         svg: SVG_NS
234     }[prefix] || null;
237 function method_caller (obj, func) {
238     return function () {
239         func.apply(obj, arguments);
240     };
244 function get_window_from_frame (frame) {
245     try {
246         var window = frame.QueryInterface(Ci.nsIInterfaceRequestor)
247             .getInterface(Ci.nsIWebNavigation)
248             .QueryInterface(Ci.nsIDocShellTreeItem)
249             .rootTreeItem
250             .QueryInterface(Ci.nsIInterfaceRequestor)
251             .getInterface(Ci.nsIDOMWindow).wrappedJSObject;
252         /* window is now an XPCSafeJSObjectWrapper */
253         window.escape_wrapper(function (w) { window = w; });
254         /* window is now completely unwrapped */
255         return window;
256     } catch (e) {
257         return null;
258     }
261 function get_buffer_from_frame (window, frame) {
262     var count = window.buffers.count;
263     for (var i = 0; i < count; ++i) {
264         var b = window.buffers.get_buffer(i);
265         if (b.top_frame == frame.top)
266             return b;
267     }
268     return null;
272 function dom_generator (document, ns) {
273     this.document = document;
274     this.ns = ns;
276 dom_generator.prototype = {
277     constructor: dom_generator,
278     element: function (tag, parent) {
279         var node = this.document.createElementNS(this.ns, tag);
280         var i = 1;
281         if (parent != null && (parent instanceof Ci.nsIDOMNode)) {
282             parent.appendChild(node);
283             i = 2;
284         }
285         for (var nargs = arguments.length; i < nargs; i += 2)
286             node.setAttribute(arguments[i], arguments[i+1]);
287         return node;
288     },
290     text: function (str, parent) {
291         var node = this.document.createTextNode(str);
292         if (parent)
293             parent.appendChild(node);
294         return node;
295     },
298     stylesheet_link: function (href, parent) {
299         var node = this.element("link");
300         node.setAttribute("rel", "stylesheet");
301         node.setAttribute("type", "text/css");
302         node.setAttribute("href", href);
303         if (parent)
304             parent.appendChild(node);
305         return node;
306     },
309     add_stylesheet: function (url) {
310         var head = this.document.documentElement.firstChild;
311         this.stylesheet_link(url, head);
312     }
316  * Generates a QueryInterface function suitable for an implemenation
317  * of an XPCOM interface.  Unlike XPCOMUtils, this uses the Function
318  * constructor to generate a slightly more efficient version.  The
319  * arguments can be either Strings or elements of
320  * Components.interfaces.
321  */
322 function generate_QI () {
323     var args = Array.prototype.slice.call(arguments).map(String).concat(["nsISupports"]);
324     var fstr = "if(" +
325         Array.prototype.map.call(args, function (x) {
326             return "iid.equals(Components.interfaces." + x + ")";
327         })
328         .join("||") +
329         ") return this; throw Components.results.NS_ERROR_NO_INTERFACE;";
330     return new Function("iid", fstr);
334 function abort (str) {
335     var e = new Error(str);
336     e.__proto__ = abort.prototype;
337     return e;
339 abort.prototype.__proto__ = Error.prototype;
342 function get_temporary_file (name) {
343     if (name == null)
344         name = "temp.txt";
345     var file = file_locator_service.get("TmpD", Ci.nsIFile);
346     file.append(name);
347     // Create the file now to ensure that no exploits are possible
348     file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
349     return file;
353 /* FIXME: This should be moved somewhere else, perhaps. */
354 function create_info_panel (window, panel_class, row_arr) {
355     /* Show information panel above minibuffer */
357     var g = new dom_generator(window.document, XUL_NS);
359     var p = g.element("vbox", "class", "panel " + panel_class, "flex", "0");
360     var grid = g.element("grid", p);
361     var cols = g.element("columns", grid);
362     g.element("column", cols, "flex", "0");
363     g.element("column", cols, "flex", "1");
365     var rows = g.element("rows", grid);
366     var row;
368     for each (let [row_class, row_label, row_value] in row_arr) {
369         row = g.element("row", rows, "class", row_class);
370         g.element("label", row,
371                   "value", row_label,
372                   "class", "panel-row-label");
373         g.element("label", row,
374                   "value", row_value,
375                   "class", "panel-row-value",
376                   "crop", "end");
377     }
378     window.minibuffer.insert_before(p);
380     p.destroy = function () {
381         this.parentNode.removeChild(this);
382     };
384     return p;
389  * Paste from the X primary selection, unless the system doesn't support a
390  * primary selection, in which case fall back to the clipboard.
391  */
392 function read_from_x_primary_selection () {
393     // Get clipboard.
394     let clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
395         .getService(Components.interfaces.nsIClipboard);
397     // Fall back to global clipboard if the system doesn't support a selection
398     let which_clipboard = clipboard.supportsSelectionClipboard() ?
399         clipboard.kSelectionClipboard : clipboard.kGlobalClipboard;
401     let flavors = ["text/unicode"];
403     // Don't barf if there's nothing on the clipboard
404     if (!clipboard.hasDataMatchingFlavors(flavors, flavors.length, which_clipboard))
405         return "";
407     // Create transferable that will transfer the text.
408     let trans = Components.classes["@mozilla.org/widget/transferable;1"]
409         .createInstance(Components.interfaces.nsITransferable);
411     for each (let flavor in flavors) {
412         trans.addDataFlavor(flavor);
413     }
414     clipboard.getData(trans, which_clipboard);
416     var data_flavor = {};
417     var data = {};
418     var dataLen = {};
419     trans.getAnyTransferData(data_flavor, data, dataLen);
421     if (data) {
422         data = data.value.QueryInterface(Components.interfaces.nsISupportsString);
423         let data_length = dataLen.value;
424         if (data_flavor.value == "text/unicode")
425             data_length = dataLen.value / 2;
426         return data.data.substring(0, data_length);
427     } else {
428         return "";
429     }
433 function predicate_alist_match (alist, key) {
434     for each (let i in alist) {
435         if (i[0](key))
436             return i[1];
437     }
438     return undefined;
442 function get_meta_title (doc) {
443     var title = doc.evaluate("//meta[@name='title']/@content", doc, xpath_lookup_namespace,
444                              Ci.nsIDOMXPathResult.STRING_TYPE , null);
445     if (title && title.stringValue)
446         return title.stringValue;
447     return null;
451 function queue () {
452     this.input = [];
453     this.output = [];
455 queue.prototype = {
456     constructor: queue,
457     get length () {
458         return this.input.length + this.output.length;
459     },
460     push: function (x) {
461         this.input[this.input.length] = x;
462     },
463     pop: function (x) {
464         let l = this.output.length;
465         if (!l) {
466             l = this.input.length;
467             if (!l)
468                 return undefined;
469             this.output = this.input.reverse();
470             this.input = [];
471             let x = this.output[l];
472             this.output.length--;
473             return x;
474         }
475     }
478 function frame_iterator (root_frame, start_with) {
479     var q = new queue, x;
480     if (start_with) {
481         x = start_with;
482         do {
483             yield x;
484             for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
485                 q.push(x.frames[i]);
486         } while ((x = q.pop()));
487     }
488     x = root_frame;
489     do {
490         if (x == start_with)
491             continue;
492         yield x;
493         for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
494             q.push(x.frames[i]);
495     } while ((x = q.pop()));
498 function xml_http_request () {
499     return Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
500         .createInstance(Ci.nsIXMLHttpRequest)
501         .QueryInterface(Ci.nsIJSXMLHttpRequest)
502         .QueryInterface(Ci.nsIDOMEventTarget);
505 var xml_http_request_load_listener = {
506   // nsIBadCertListener2
507   notifyCertProblem: function SSLL_certProblem (socketInfo, status, targetSite) {
508     return true;
509   },
511   // nsISSLErrorListener
512   notifySSLError: function SSLL_SSLError (socketInfo, error, targetSite) {
513     return true;
514   },
516   // nsIInterfaceRequestor
517   getInterface: function SSLL_getInterface (iid) {
518     return this.QueryInterface(iid);
519   },
521   // nsISupports
522   //
523   // FIXME: array comprehension used here to hack around the lack of
524   // Ci.nsISSLErrorListener in 2007 versions of xulrunner 1.9pre.
525   // make it a simple generateQI when xulrunner is more stable.
526   QueryInterface: XPCOMUtils.generateQI(
527       [i for each (i in [Ci.nsIBadCertListener2,
528                          Ci.nsISSLErrorListener,
529                          Ci.nsIInterfaceRequestor])
530        if (i)])
535  * Coroutine interface for sending an HTTP request and waiting for the
536  * response. (This includes so-called "AJAX" requests.)
538  * @param lspec (required) a load_spec object or URI string (see load-spec.js)
540  * The request URI is obtained from this argument. In addition, if the
541  * load spec specifies post data, a POST request is made instead of a
542  * GET request, and the post data included in the load spec is
543  * sent. Specifically, the request_mime_type and raw_post_data
544  * properties of the load spec are used.
546  * @param $user (optional) HTTP user name to include in the request headers
547  * @param $password (optional) HTTP password to include in the request headers
549  * @param $override_mime_type (optional) Force the response to be interpreted
550  *                            as having the specified MIME type.  This is only
551  *                            really useful for forcing the MIME type to be
552  *                            text/xml or something similar, such that it is
553  *                            automatically parsed into a DOM document.
554  * @param $headers (optional) an array of [name,value] pairs (each specified as
555  *                 a two-element array) specifying additional headers to add to
556  *                 the request.
558  * @returns After the request completes (either successfully or with an error),
559  *          the nsIXMLHttpRequest object is returned.  Its responseText (for any
560  *          arbitrary document) or responseXML (if the response type is an XML
561  *          content type) properties can be accessed to examine the response
562  *          document.
564  * If an exception is thrown to the continutation (which can be obtained by the
565  * caller by calling yield CONTINUATION prior to calling this function) while the
566  * request is in progress (i.e. before this coroutine returns), the request will
567  * be aborted, and the exception will be propagated to the caller.
569  **/
570 define_keywords("$user", "$password", "$override_mime_type", "$headers");
571 function send_http_request (lspec) {
572     // why do we get warnings in jsconsole unless we initialize the
573     // following keywords?
574     keywords(arguments, $user = undefined, $password = undefined,
575              $override_mime_type = undefined, $headers = undefined);
576     if (! (lspec instanceof load_spec))
577         lspec = load_spec(lspec);
578     var req = xml_http_request();
579     var cc = yield CONTINUATION;
580     var aborting = false;
581     req.onreadystatechange = function send_http_request__onreadysatechange () {
582         if (req.readyState != 4)
583             return;
584         if (aborting)
585             return;
586         cc();
587     };
589     if (arguments.$override_mime_type)
590         req.overrideMimeType(arguments.$override_mime_type);
592     var post_data = load_spec_raw_post_data(lspec);
594     var method = post_data ? "POST" : "GET";
596     req.open(method, load_spec_uri_string(lspec), true, arguments.$user, arguments.$password);
597     req.channel.notificationCallbacks = xml_http_request_load_listener;
599     for each (let [name,value] in arguments.$headers) {
600         req.setRequestHeader(name, value);
601     }
603     if (post_data) {
604         req.setRequestHeader("Content-Type", load_spec_request_mime_type(lspec));
605         req.send(post_data);
606     } else
607         req.send(null);
609     try {
610         yield SUSPEND;
611     } catch (e) {
612         aborting = true;
613         req.abort();
614         throw e;
615     }
617     // Let the caller access the status and reponse data
618     yield co_return(req);
623  * scroll_selection_into_view takes an editable element, and scrolls it so
624  * that the selection (or insertion point) are visible.
625  */
626 function scroll_selection_into_view (field) {
627     if (field.namespaceURI == XUL_NS)
628         field = field.inputField;
629     try {
630         field.QueryInterface(Ci.nsIDOMNSEditableElement)
631             .editor
632             .selectionController
633             .scrollSelectionIntoView(
634                 Ci.nsISelectionController.SELECTION_NORMAL,
635                 Ci.nsISelectionController.SELECTION_FOCUS_REGION,
636                 true);
637     } catch (e) {
638         // we'll get here for richedit fields
639     }
644  * build_url_regex builds a regular expression to match URLs for a given
645  * web site.
647  * Both the $domain and $path arguments can be either regexes, in
648  * which case they will be matched as is, or strings, in which case
649  * they will be matched literally.
651  * $tlds specifies a list of valid top-level-domains to match, and
652  * defaults to .com. Useful for when e.g. foo.org and foo.com are the
653  * same.
655  * If $allow_www is true, www.domain.tld will also be allowed.
656  */
657 define_keywords("$domain", "$path", "$tlds", "$allow_www");
658 function build_url_regex () {
659     function regex_to_string (obj) {
660         if (typeof obj == "object" && "source" in obj)
661             return obj.source;
662         return quotemeta(obj);
663     }
665     keywords(arguments, $path = "", $tlds = ["com"], $allow_www = false);
666     var domain = regex_to_string(arguments.$domain);
667     if(arguments.$allow_www) {
668         domain = "(?:www\.)?" + domain;
669     }
670     var path   = regex_to_string(arguments.$path);
671     var tlds   = arguments.$tlds;
672     var regex = "^https?://" + domain + "\\." + choice_regex(tlds) + "/" + path;
673     return new RegExp(regex);
677 function compute_url_up_path (url) {
678     var new_url = Cc["@mozilla.org/network/standard-url;1"]
679         .createInstance (Ci.nsIURL);
680     new_url.spec = url;
681     var up;
682     if (new_url.param != "" || new_url.query != "")
683         up = new_url.filePath;
684     else if (new_url.fileName != "")
685         up = ".";
686     else
687         up = "..";
688     return up;
692 function url_path_trim (url) {
693     var uri = make_uri(url);
694     uri.spec = url;
695     uri.path = "";
696     return uri.spec;
699 /* possibly_valid_url returns true if the string might be a valid
700  * thing to pass to nsIWebNavigation.loadURI.  Currently just checks
701  * that there's no whitespace in the middle and that it's not entirely
702  * whitespace.
703  */
704 function possibly_valid_url (url) {
705     return !(/\S\s+\S/.test(url)) && !(/^\s*$/.test(url));
710  * Convenience function for making simple XPath lookups in a document.
712  * @param doc The document to look in.
713  * @param exp The XPath expression to search for.
714  * @return The XPathResult object representing the set of found nodes.
715  */
716 function xpath_lookup (doc, exp) {
717     return doc.evaluate(exp, doc, null, Ci.nsIDOMXPathResult.ANY_TYPE, null);
721 /* get_contents_synchronously returns the contents of the given
722  * url (string or nsIURI) as a string on success, or null on failure.
723  */
724 function get_contents_synchronously (url) {
725     var ioService=Cc["@mozilla.org/network/io-service;1"]
726         .getService(Ci.nsIIOService);
727     var scriptableStream=Cc["@mozilla.org/scriptableinputstream;1"]
728         .getService(Ci.nsIScriptableInputStream);
729     var channel;
730     var input;
731     try {
732         if (url instanceof Ci.nsIURI)
733             channel = ioService.newChannelFromURI(url);
734         else
735             channel = ioService.newChannel(url, null, null);
736         input=channel.open();
737     } catch (e) {
738         return null;
739     }
740     scriptableStream.init(input);
741     var str=scriptableStream.read(input.available());
742     scriptableStream.close();
743     input.close();
744     return str;
749  * dom_add_class adds a css class to the given dom node.
750  */
751 function dom_add_class (node, cssclass) {
752     if (node.className) {
753         var cs = node.className.split(" ");
754         if (cs.indexOf(cssclass) != -1)
755             return;
756         cs.push(cssclass);
757         node.className = cs.join(" ");
758     } else
759         node.className = cssclass;
763  * dom_remove_class removes the given css class from the given dom node.
764  */
765 function dom_remove_class (node, cssclass) {
766     if (! node.className)
767         return;
768     var classes = node.className.split(" ");
769     classes = classes.filter(function (x) { return x != cssclass; });
770     node.className = classes.join(" ");
775  * dom_node_flash adds the given cssclass to the node for a brief interval.
776  * this class can be styled, to create a flashing effect.
777  */
778 function dom_node_flash (node, cssclass) {
779     dom_add_class(node, cssclass);
780     call_after_timeout(
781         function () {
782             dom_remove_class(node, cssclass);
783         },
784         400);
789  * data is an an alist (array of 2 element arrays) where each pair is a key
790  * and a value.
792  * The return type is a mime input stream that can be passed as postData to
793  * nsIWebNavigation.loadURI.  In terms of Conkeror's API, the return value
794  * of this function is of the correct type for the `post_data' field of a
795  * load_spec.
796  */
797 function make_post_data (data) {
798     data = [(encodeURIComponent(pair[0])+'='+encodeURIComponent(pair[1]))
799             for each (pair in data)].join('&');
800     data = string_input_stream(data);
801     return mime_input_stream(
802         data, [["Content-Type", "application/x-www-form-urlencoded"]]);
807  * Centers the viewport around a given element.
809  * @param win  The window to scroll.
810  * @param elem The element arund which we put the viewport.
811  */
812 function center_in_viewport (win, elem) {
813     let point = abs_point(elem);
815     point.x -= win.innerWidth / 2;
816     point.y -= win.innerHeight / 2;
818     win.scrollTo(point.x, point.y);
823  * Simple predicate returns true if elem is an nsIDOMNode or
824  * nsIDOMWindow.
825  */
826 function element_dom_node_or_window_p (elem) {
827     if (elem instanceof Ci.nsIDOMNode)
828         return true;
829     if (elem instanceof Ci.nsIDOMWindow)
830         return true;
831     return false;
835  * Given a hook name, a buffer and a function, waits until the buffer document
836  * has fully loaded, then calls the function with the buffer as its only
837  * argument.
839  * @param {String} The hook name.
840  * @param {buffer} The buffer.
841  * @param {function} The function to call with the buffer as its argument once
842  *                   the buffer has loaded.
843  */
844 function do_when (hook, buffer, fun) {
845     if (buffer.browser.webProgress.isLoadingDocument)
846         add_hook.call(buffer, hook, fun);
847     else
848         fun(buffer);
853  * evaluate string s as javascript in the 'this' scope in which evaluate
854  * is called.
855  */
856 function evaluate (s) {
857     try {
858         var temp = get_temporary_file("conkeror-evaluate.tmp.js");
859         write_text_file(temp, s);
860         var url = make_uri(temp).spec;
861         return load_url(url, this);
862     } finally {
863         if (temp && temp.exists())
864             temp.remove(false);
865     }
868 provide("utils");