Search completed in 0.93 seconds.
Web Replay
behaviors. ipc integration allows a replaying process to communicate with the chrome process using ipdl and shared memory. the rewind infrastructure allows a replaying process to restore a previous state, while still maintaining communication with the chrome process. debugger integration allows the js debugger to read the information it needs from a replaying process and control the process's
execution (resume/rewind). the debugger is not allowed to change the replaying process's observable state. record/replay infrastructure broadly, reliable record/replay is achieved by controlling for non-determinism in the browser. this non-determinism originates from two sources: intra-thread and inter-thread. intra-thread non-deterministic behaviors are non-deterministic even in the absence of actio...
...record/replay infrastructure broadly, reliable record/replay is achieved by controlling for non-determinism in the browser. this non-determinism originates from two sources: intra-thread and inter-thread. intra-thread non-deterministic behaviors are non-deterministic even in the absence of actions by other threads, and inter-thread non-deterministic behaviors are those affected by interleaving
execution with other threads, and which always behave the same given the same interleaving. intra-thread non-determinism is recorded and later replayed for each thread. these behaviors mainly originate from system calls (i/o and such). inter-thread non-determinism is handled by first assuming the program is data race free: shared memory accesses which would otherwise race are either protected by locks o...
...ipple effects in other areas. mainly, pointer values may differ between recording and replay, and the points where gcs occur, and the set of objects collected, may differ. this non-determinism is prevented from spreading too far with the following techniques: different pointer values can affect the internal layout of hash tables. ...
...And 15 more matches
Index - Web APIs
removetrack event event the removetrack event is fired when a track is removed from an audiotracklist. 202 audioworklet api, audio, audioworklet, experimental, interface, reference, web audio api, worklet the audioworklet interface of the web audio api is used to supply custom audio processing scripts. ...
...each baseaudiocontext has a single audioworklet available under the audioworklet property, which runs its code in a single audioworkletglobalscope. ...
...toothcharacteristicproperties interface of the the web bluetooth api provides an object provides propertieds of a particular bluetoothremotegattcharacteristic. 308 bluetoothdevice api, bluetooth, bluetoothdevice, experimental, interface, reference, web bluetooth api the bluetoothdevice interface of the web bluetooth api represents a bluetooth device inside a particular script
execution environment. 309 bluetoothdevice.gatt api, bluetoothdevice, experimental, gatt server, property, reference the bluetoothdevice.gatt read-only property returns a reference to the device's bluetoothremotegattserver. 310 bluetoothdevice.name api, bluetooth, bluetoothdevice, experimental, property, reference, web bluetooth api, name the bluetoothdevice.name r...
...And 13 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
eb api (settimeout() and setinterval()), the javascript environment provided by web browsers has gradually advanced to include powerful features that enable scheduling of tasks, multi-threaded application development, and so forth. to understand where queuemicrotask() comes into play here, it's helpful to understand how the javascript runtime operates when scheduling and running code. javascript
execution contexts note: the details here are generally not important to most javascript programmers. this information is provided as a basis for why microtasks are useful and how they function; if you don't care, you can skip this and come back later if you find that you need to. when a fragment of javascript code runs, it runs inside an
execution context. there are three types of code that create a n...
...ntexts note: the details here are generally not important to most javascript programmers. this information is provided as a basis for why microtasks are useful and how they function; if you don't care, you can skip this and come back later if you find that you need to. when a fragment of javascript code runs, it runs inside an
execution context. there are three types of code that create a new
execution context: the global context is the
execution context created to run the main body of your code; that is, any code that exists outside of a javascript function. each function is run within its own
execution context. this is frequently referred to as a "local context." using the ill-advised eval() function also creates a new
execution context. each context is, in essence, a level of scope wi...
...ext created to run the main body of your code; that is, any code that exists outside of a javascript function. each function is run within its own
execution context. this is frequently referred to as a "local context." using the ill-advised eval() function also creates a new
execution context. each context is, in essence, a level of scope within your code. as one of these code segments begins
execution, a new context is constructed in which to run it; that context is then destroyed when the code exits. consider the javascript program below: let outputelem = document.getelementbyid("output"); let userlanguages = { "mike": "en", "teresa": "es" }; function greetuser(user) { function localgreeting(user) { let greeting; let language = userlanguages[user]; switch(language) { ...
...And 11 more matches
DeferredTask.jsm
ending obsolete since gecko 28 check the current task state. bool ispending(); return value returns true if pending, false otherwise. start obsolete since gecko 28 start (or postpone) task. void start(); flush obsolete since gecko 28 perform any postponed task immediately. void flush(); cancel obsolete since gecko 28 cancel any pending task. void cancel(); arm request the
execution of the task after the delay specified on construction. multiple calls don't introduce further delays. if the task is running, the delay will start when the current
execution finishes. the task will always be executed on a different tick of the event loop, even if the delay specified on construction is zero. multiple "arm" calls within the same tick of the event loop are guaranteed to result in a...
...in fact, doing that would often result in duplicate processing or logging. ...
...in fact, doing that would often result in duplicate processing or logging. if a special operation or error logging is needed on completion, it can be better handled from within the task itself, for example using a try/catch/finally clause in the task. ...
...And 8 more matches
Using Breakpoints in Venkman - Archive of obsolete content
this article describes breakpoints in javascript and how to use venkman to set and examine breakpoints. ...
...this article describes breakpoints in javascript and how to use venkman to set and examine breakpoints. ...
... to need breakpoints. types of breakpoints venkman has two types of breakpoints. the first, and most common, is called the "hard" breakpoint. a hard breakpoint represents an actual trap instruction included in the pseudocode of a compiled function. hard breakpoints can only exist in the context of a function currently "live" in the browser. hard breakpoints are the ones that actually stop program
execution. the second type of breakpoint, the "future" breakpoint, represents a promise from venkman to set a hard breakpoint as soon as it is possible. future breakpoints are used when you want to stop in a script that has not yet been compiled. the most common use of future breakpoints is to stop in a "top level" script (script that executes outside of any function), or script that executes during the on...
...And 6 more matches
Index
shell, see the spidermonkey build documentation or download a compiled binary for your platform from the nightly builds. 13 jit optimization outcomes beginner, firefox, intro, needscontent, spidermonkey spidermonkey's optimizing jit, ionmonkey, uses different optimization strategies to speed up various operations. the most typical operations that are relevant for fast program
execution are property accesses and function calls. 14 jit optimization strategies junk, spidermonkey spidermonkey's optimizing jit, ionmonkey, uses various strategies to optimize operations. the most commonplace operations that are relevant for fast program
execution are property accesses and function calls. 15 jsapi cookbook spidermonkey this article shows the js...
...holds a variable-size rooted array of type t. 27 js::booleanvalue jsapi reference, reference, référence(2), spidermonkey js::booleanvalue converts a c boolean of type bool to js::value, the type of javascript values. 28 js::call jsapi reference, reference, spidermonkey js::call calls a specified function, fun, on an object, thisobj. in terms of function
execution, the object is treated as this. 29 js::callargs jsapi reference, reference, référence(2), spidermonkey js::callargs is helper class encapsulating access to the callee, this value, arguments, and argument count for a function call. 30 js::clonefunctionobject jsapi reference, reference, référence(2), spidermonkey js::clonefunctionobject creates a new fu...
... scopechain as its enclosing scope. if scopechain is omitted, it creates a new function object in cx's global. this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. 31 js::compile jsapi reference, reference, référence(2), spidermonkey js::compile compiles a script, srcbuf, chars, bytes, or file, for
execution. 32 js::compilefunction jsapi reference, reference, référence(2), spidermonkey js::compilefunction compiles a function from a text string chars, bytes, or srcbuf. 33 js::compileoffthread jsapi reference, reference, référence(2), spidermonkey js::compileoffthread compiles a script, chars for
execution. 34 js::compileoptions jsapi referen...
...And 6 more matches
Bytecode Descriptions
n to the caller. when a generator is called, its script starts running, like any other js function, because functiondeclarationinstantation and other generator object setup are implemented mostly in bytecode. however, the functionbody of the generator is not supposed to start running until the first .next() call, so after setup the script suspends itself: the "initial yield". later, when resuming
execution, rval, gen and resumekind will receive the values passed in by jsop::resume. resumekind is the generatorresumekind stored as an int32 value. this instruction must appear only in scripts for generators and async generators. gen must be the generator object for the current frame. it must not have been previously suspended. the resume point indicated by resumeindex must be the next instruction in th...
...'s return value slot is returned to the caller. it should be an object of the form {value: returnvalue, done: true}. if the current function is an async function or async generator, the frame's return value slot must contain the current frame's result promise, which must already be resolved or rejected. yield operands: (uint24_t resumeindex) stack: rval1, gen ⇒ rval2, gen, resumekind suspend
execution of the current generator or async generator, returning rval1. for non-async generators, rval1 should be an object of the form {value: valuetoyield, done: true}. for async generators, rval1 should be the value to yield, and the caller is responsible for creating the iterator result object (under js::asyncgeneratoryield). this instruction must appear only in scripts for generators and async generat...
...uld be the value to yield, and the caller is responsible for creating the iterator result object (under js::asyncgeneratoryield). this instruction must appear only in scripts for generators and async generators. gen must be the generator object for the current stack frame. the resume point indicated by resumeindex must be the next instruction in the script, which must be afteryield. when resuming
execution, rval2, gen and resumekind receive the values passed in by jsop::resume. implements: generatoryield and asyncgeneratoryield. format: jof_resumeindex isgenclosing stack: val ⇒ val, res pushes a boolean indicating whether the top of the stack is magicvalue(js_generator_closing). asyncawait stack: value, gen ⇒ promise arrange for this async function to resume asynchronously when value beco...
...And 5 more matches
Debugger.Frame - Firefox Developer Tools
for a given debugger instance, spidermonkey creates only one debugger.frame instance for a given visible frame. every handler method called while the debuggee is running in a given frame is given the same frame object. ...
...call frame, this property throws a typeerror. older the next-older visible frame, in which control will resume when this frame completes. if there is no older frame, this is null. depth the depth of this frame, counting from oldest to youngest; the oldest frame has a depth of zero. live true if the frame this debugger.frame instance refers to is still on the stack; false if it has completed
execution or been popped in some other way. script the script being executed in this frame (a debugger.script instance), or null on frames that do not represent calls to debuggee code. on frames whose callee property is not null, this is equal to callee.script. offset the offset of the bytecode instruction currently being executed in script, or undefined if the frame’s script property is null. for a ...
......
...And 5 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
instances of the object are drawn. 79 client hints client hints, glossary, performance, reference, web performance client hints are a set of http request header fields for proactive content negotiation allowing clients to indicate a list of device and agent specific preferences. 80 closure codingscripting, glossary the binding which defines the scope of
execution. in javascript, functions create a closure context. 81 code splitting glossary, reference, web performance, code splitting, latency code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel. 82 codec glossary, webmechanics a codec (a blend word derived from "coder-decoder") is a program, a...
... and organizing a collection of instructions. these tell a computer/software program what to do in a language which the computer understands. these instructions come in the form of many different languages such as c++, java, javascript, html, python, ruby, and rust. 86 conditional beginner, codingscripting, glossary a condition is a set of rules that can interrupt normal code
execution or change it, depending on whether the condition is completed or not. 87 constant codingscripting, constant, glossary a constant is a value that the programmer cannot change, for example numbers (1, 2, 42). with variables, on the other hand, the programmer can assign a new value to a variable name already in use. 88 constructor codingscripting, glossary a...
...he content of the body of themessage. headers like content-length, content-language, content-encoding are entities headers. 135 event codingscripting, glossary events are assets generated by dom elements, which can be manipulated by a javascript code. 136 exception beginner, codingscripting, glossary an exception is a condition that interrupts normal code
execution. in javascript syntax errors are a very common source of exceptions. 137 expando codingscripting, javascript, reference, expando expando properties are properties added to dom nodes with javascript, where those properties are not part of the object's dom specification: 138 ftp codingscripting, ftp, glossary, protocol ftp (file transfer protocol) was the s...
...And 4 more matches
Introduction to NSPR
a thread has a limited number of resources that it truly owns. these resources include the thread stack and the cpu register set (including pc). to an nspr client, a thread is represented by a pointer to an opaque structure of type p...
...ions begin with pr_ and are followed by intercap-style declarations, like this: pr_read, pr_jointhread preprocessor macros begin with the letters pr and are followed by all uppercase characters separated with the underscore character (_), like this: pr_bytes_per_short, pr_extern nspr threads nspr provides an
execution environment that promotes the use of lightweight threads. each thread is an
execution entity that is scheduled independently from other threads in the same process. a thread has a limited number of resources that it truly owns. these resources include the thread stack and the cpu register set (including pc). to an nspr client, a thread is represented by a pointer to an opaque structure of type prthread. a thread is created by an explicit client request and remains a valid, indepe...
...y that is scheduled independently from other threads in the same process. a thread has a limited number of resources that it truly owns. these resources include the thread stack and the cpu register set (including pc). to an nspr client, a thread is represented by a pointer to an opaque structure of type prthread. a thread is created by an explicit client request and remains a valid, independent
execution entity until it returns from its root function or the process abnormally terminates. (prthread and functions for creating and manipulating threads are described in detail in threads.) nspr threads are lightweight in the sense that they are cheaper than full-blown processes, but they are not free. they achieve the cost reduction by relying on their containing process to manage most of the resourc...
...And 3 more matches
Rhino Debugger
des a source-level debugger for debugging javascript scripts. the debugger is itself a java program which you may run as java org.mozilla.javascript.tools.debugger.main [options] [filename.js] [script-arguments] where the options are the same as the shell. the rhino javascript debugger can debug scripts running in multiple threads and provides facilities to set and clear breakpoints, control
execution, view variables, and evaluate arbitrary javascript code in the current scope of an executing script. console window the debugger redirects the system.out, system.in, and system.err streams to an internal javascript console window which provides an editable command line for you to enter javascript code and view system output. the console window maintains a history of the commands you have ente...
...compiled and displayed in a new window. running scripts you may select the file->run menu item on the menu bar to execute javascript scripts contained in files. this action will display a file-selection dialog box prompting you for the location of a script to execute. the loaded script will be run in a new thread and control will be given to the debugger on its first instruction. controlling
execution the debugger provides the following facilities for you to control the
execution of scripts you are debugging: step into to single step entering any function calls, you may do any of the following: select the debug->step into menu item on the menu bar press the step into button on the toolbar press the f11 key on the keyboard
execution will resume. if the current line in the scri...
...ontrol will return to the debugger upon entry into the function. otherwise control will return to the debugger at the next line in the current function. ...
...And 3 more matches
Shell global objects
engine and should be lazily loaded from the embedding as-needed. loadbytecode if true, and if the source is a cacheentryobject, the bytecode would be loaded and decoded from the cache entry instead of being parsed, then it would be executed as usual. savebytecode if true, and if the source is a cacheentryobject, the bytecode would be encoded and saved into the cache entry after the script
execution. asserteqbytecode if true, and if both loadbytecode and savebytecode are true, then the loaded bytecode and the encoded bytecode are compared. and an assertion is raised if they differ. run('foo.js') run the file named by the first argument, returning the number of of milliseconds spent compiling and executing it. read('bar.js') reads the file named by the first argument, returning...
...urn its value. offthreadcompilemodule(code) compile code on a helper thread. to wait for the compilation to finish and get the module object, call finishoffthreadmodule. finishoffthreadmodule() wait for off-thread compilation to complete. if an error occurred, throw the appropriate exception; otherwise, return the module object timeout([seconds], [func]) get/set the limit in seconds for the
execution time for the current context. a negative value (default) means that the
execution time is unlimited. if a second argument is provided, it will be invoked when the timer elapses. calling this function will replace any callback set by setinterruptcallback. interruptif(cond) requests interrupt callback if cond is true. if a callback function is set via timeout or setinterruptcallback, it will be c...
...e interrupt handler. setinterruptcallback(func) sets func as the interrupt callback function. calling this function will replace any callback set by timeout. enablelastwarning() enable storing the last warning. disablelastwarning() disable storing the last warning. getlastwarning() returns an object that represents the last warning. clearlastwarning() clear the last warning. elapsed()
execution time elapsed for the current thread. decompilefunction(func) decompile a function. decompilethis() decompile the currently executing script. thisfilename() return the filename of the current script newglobal([options]) return a new global object in a new compartment. if options is given, it may have any of the following properties: samezoneas the compartment will be in the same zone...
...And 3 more matches
Storage
write in the sql. the use of numerical indexes for parameters is strongly discouraged in javascript where named parameters are much easier to use. binding multiple sets of parameters starting in gecko 1.9.2 (firefox 3.6), there's a new, more convenient way to bind multiple sets of parameters at once prior to executing your statement asynchronously. this api is only available for asynchronous
execution. let stmt = dbconn.createstatement("insert into table_name (value) values(:value)"); let params = stmt.newbindingparamsarray(); for (let i = 0; i < 10; i++) { let bp = params.newbindingparams(); bp.bindbyname("value", i); params.addparams(bp); } stmt.bindparameters(params); you can attach multiple sets of bindings to a statement by adding multiple mozistoragebindingparams objects to the ...
...(bp); } stmt.bindparameters(params); you can attach multiple sets of bindings to a statement by adding multiple mozistoragebindingparams objects to the array of parameter lists, adding each one through calls to the mozistoragebindingparamsarray.addparams(). once all the parameters are set up, a single call to mozistoragestatement.bindparameters() will ensure that the parameters are bound before
execution. you can then execute the statement asynchronously, and the statement will get each set of bindings bound to it before
execution asynchronously. executing a statement you may execute statements either synchronously (which is supported in firefox gecko 1.8 and 1.9) or asynchronously (starting in gecko 1.9.1). if your code needs to work with applications based on gecko 1.8 or 1.9, you should the ...
...multiple statements can be executed in a transaction by calling mozistorageconnection.executeasync() on the connection and passing in an array of statements. ...
...And 3 more matches
Migrating from Firebug - Firefox Developer Tools
splayed in the events side panel in firebug. in the devtools they are shown when clicking the small 'ev' icon besides an element within the node view. both tools allow to display wrapped event listeners (e.g. listeners wrapped in jquery functions). to improve the ui of the devtools, there is also a request to add an events side panel to them like the one in firebug (see bug 1226640). stop script
execution on dom mutation in firebug you can break on dom mutations, that means that when an element is changed, the script
execution is stopped at the related line within the javascript file, which caused the change. this feature can globally be enabled via the break on mutate button, or individually for each element and for different types of changes like attribute changes, content changes or element re...
... search for elements via css selectors or xpaths firebug allows to search for elements within the html panel via css selectors or xpaths. also the devtools' inspector panel allows to search for css selectors. it even displays a list with matching ids or classes. ...
...to remove single breakpoints or all of them at once. they do currently only allow to set script breakpoints. xhr, dom, cookie and error breakpoints are not supported yet (see bug 821610, bug 1004678, bug 895893 and bug 1165010). while there are no breakpoints for single javascript errors, there is a setting pause on exceptions within the debugger panel options. step through code once the script
execution is stopped, you can step through the code using the continue (f8), step over (f10), step into (f11) and step out (shift+f11) options. they work the same in both tools. examine call stack when the script
execution is paused, firebug displays the function call stack within its stack side panel. in there the functions are listed together with their call parameters. in the devtools the function cal...
...And 3 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
a microtask is a short function which is executed after the function or program which created it exits and only if the javascript
execution stack is empty, but before returning control to the event loop being used by the user agent to drive the script's
execution environment. this event loop may be either the browser's main event loop or the event loop driving a web worker. this lets the given function run without the risk of interfering with another script's
execution, yet also ensures that the microtask runs before the user agent has the opportunity to react to actions taken by the microtask. javascript promises and the mutation observer api both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping...
...ions. also, creating and destroying promises takes additional overhead both in terms of time and memory that a function which properly enqueues microtasks avoids. simply pass the javascript function to call while the context is handling microtasks into the queuemicrotask() method, which is exposed on the global context as defined by either the window or worker interface, depending on the current
execution context. queuemicrotask(() => { /* code to run in the microtask here */ }); the microtask function itself takes no parameters, and does not return a value. when to use microtasks in this section, we'll take a look at scenarios in which microtasks are particularly useful. generally, it's about capturing or checking results, or performing cleanup, after the main body of a javascript executio...
...acks are processed. when is that useful? the main reason to use microtasks is simply that: to ensure consistent ordering of tasks, even when results or data is available synchronously, but while simultaneously reducing the risk of user-discernible delays in operations. ensuring ordering on conditional use of promises one situation in which microtasks can be used to ensure that the ordering of
execution is always consistent is when promises are used in one clause of an if...else statement (or other conditional statement), but not in the other clause. consider code such as this: customelement.prototype.getdata = url => { if (this.cache[url]) { this.data = this.cache[url]; this.dispatchevent(new event("load")); } else { fetch(url).then(result => result.arraybuffer()).then(data => ...
...And 3 more matches
Index - Archive of obsolete content
ul-app information about the application on which your add-on is running. 112 tabs/utils functions for working with xul tabs and the xul tabbrowser object. 113 test/assert add-on sdk, jpm implements the assert interface defined in the commonjs unit testing specification version 1.1. 114 test/harness test harness setup and
execution. 115 test/httpd an http server for the mozilla platform, which can be used in unit tests. 116 test/runner sets up unit tests. 117 test/utils helper methods used in the commonjs unit testing suite. 118 ui/button/action add a button to the firefox user interface. 119 ui/button/toggle add a ...
... ...
...ns this page will help guide you to the information you need in order to create add-ons for firefox, thunderbird, or other software based on the mozilla platform, as well as how to distribute your add-ons. 230 displaying web content in an extension without security issues extensions, security, xmlhttprequest, xul one of the most common security issues with extensions is
execution of remote code in privileged context. a typical example is an rss reader extension that would take the content of the rss feed (html code), format it nicely and insert into the extension window. the issue that is commonly overlooked here is that the rss feed could contain some malicious javascript code and it would then execute with the privileges of the extension — meaning that it would get fu...
...And 2 more matches
Index
underlying context wrapped by this jsdicontext. top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false| otherwise. this attribute is only valid for contexts which implement nsiscriptcontext. setting or getting this attribute on any other context will throw a ns_error_no_interface exception. stack frame objects. these are only valid inside the jsdi
executionhook which gave it to you. after you return from that handler the bottom frame, and any frame you found attached through it, are invalidated via the jsdiephemeral interface. once a jsdistackframe has been invalidated all method and property accesses will throw a ns_error_not_available exception. 193 moziasyncfavicons interfaces, interfaces:scriptable, places nsifaviconservice ...
...ces:scriptable, storage the mozistoragependingstatement interface represents a pending asynchronous database statement, and offers the cancel() method which allows you to cancel the pending statement. 212 mozistorageprogresshandler interfaces, storage, xpcom, xpcom api reference the mozistorageprogresshandler interface lets storage consumers receive callbacks during the
execution of sqlite requests. 213 mozistorageresultset interfaces, storage the mozistorageresultset interface represents a set of results from a storage statement. 214 mozistoragerow interfaces, storage the mozistoragerow interface represents a row in the result set from a storage database query. 215 mozistorageservice interfaces, interfaces:scriptab...
...interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom interface reference an input stream may be "blocking" or "non-blocking" (see the isnonblocking() method). a blocking input stream may suspend the calling thread in order to satisfy a call to close(), available(), read(), or readsegments(). a non-blocking input stream, on the other hand, must not block the calling thread of
execution. 695 available no summary! 696 close no summary! 697 isnonblocking no summary! 698 read no summary! 699 readsegments no summary! 700 nsiinputstreamcallback interfaces, interfaces:scriptable, streams, xpcom, xpcom interface reference called to indicate that the stream ...
...And 2 more matches
mozIStorageConnection
sing the connection on multiple threads. schemaversion long the schema version of the database. this should not be used until the database is ready. the version will be reported as 0 if it is not set. transactioninprogress boolean returns true if there is a transaction in progress on the database. otherwise returns false. read only. constants transaction
execution time constants. constant value description transaction_deferred 0 no database lock is obtained until the first statement is run. transaction_immediate 1 a reserved lock is obtained on the database. transaction_exclusive 2 an exclusive lock is obtained on the database. sqlite database page size constant constant value...
...ion_deferred. void begintransaction(); parameters none. begintransactionas() this method starts a new transaction of the given transaction type. see the sqlite documentation on transactions for more details. in javascript, managing transactions can be difficult when you are using the same connection on different threads, or are using a combination of asynchronous and synchronous statement
execution. the best way to deal with this is to only execute your statements asynchronously using mozistorageconnection.executeasync(). this method will manage the transactions for you, so you don't have to worry about them. note: the database engine does not support nested transactions, so attempting to start a transaction when one is already active will throw an exception. void begintransactionas( ...
...reate, as seen in sql. anumarguments the number of arguments the function takes. pass -1 for variable-argument functions. afunction the instance of mozistorageaggregatefunction that implements the function. createasyncstatement() creates a mozistorageasyncstatement for the given sql expression. an asynchronous statement can only be used to dispatch asynchronous requests to the asynchronous
execution thread and cannot be used to take any synchronous actions on the database. the expression may use "?#" to indicate sequentially numbered parameters (?1, ?2, etc) or ":name" to indicate named parameters. javascript callers should use named parameters. mozistorageasyncstatement createasyncstatement( in autf8string asqlstatement ); parameters asqlstatement the sql statement to execute. ...
...And 2 more matches
mozIStorageStatement
from. return value an autf8string with the of the column name for the specified index. getcolumnindex() obtains the index of the column with the specified name. unsigned long getcolumnindex( in autf8string aname ); parameters aname name of the column. return value the zero-based numerical index for the column to get data from. reset() resets the bound parameters and statement
execution state. this must be called before reusing the statement. note: javascript callers should always wrap their
execution in a try block, and have a reset statement in a finally block. see the overview document on storage for more details. void reset() escapestringforlike() escapes a string for sql like search. note: consumers will have to use same escape char when doing statements such as: ...
... executeasync(). note: starting in gecko 2.0, this method returns ns_error_unexpected if the specified mozistoragebindingparamsarray is empty. void bindparameters( in mozistoragebindingparamsarray aparameters ); parameters aparameters the mozistoragebindingparamsarray object containing one or more mozistoragebindingparams objects with the parameters to be bound to the statement prior to
execution. bindutf8stringparameter() binds a utf8string to the specified index. void bindutf8stringparameter( in unsigned long aparamindex, in autf8string avalue ); parameters aparamindex the zero-based numerical index for the parameter to be bound. this will be one less than the number used in the sql (<code>?1</code> maps to <code>0</code>, and so on). avalue to be bound to the specified ...
...ameter( in unsigned long aparamindex, [array,const,size_is(avaluesize)] in octet avalue, in unsigned long avaluesize ); parameters aparamindex the zero-based numerical index for the parameter to be bound. this will be one less than the number used in the sql (<code>?1</code> maps to <code>0</code>, and so on). avalue to be bound to the specified index. avaluesize size of avalue.
execution functions these functions are discussed in more detail with sample code in the overview document. executeasync() starts the
execution of a query asynchronously using the currently bound parameters. the optional callback routine receives notifications about the progress of the query. for sample code and more details, see the overview document. note: the statement does not have to be reset befo...
...And 2 more matches
nsIZipWriter
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) once all the operations you wish to perform are added to the queue, a call to processqueue() will perform the operations in the order they were added to the queue. ...
...y to add to the zip file. this is the path it will be located at within the zip file. note: you must use forward slashes ('/') in the path. amodtime the modification time of the entry in microseconds. acompression one of the compression constants, indicating the compression method to use. achannel the channel from which to get the data. aqueue if true, the operation is queued for later
execution. if false, the operation is performed immediately. will be performed when processqueue() is called. exceptions thrown ns_error_not_initialized no zip file is open. ns_error_file_already_exists the specified path already exists in the zip file. ns_error_in_progress the zip writer is already performing another operation. addentrydirectory() adds a new directory entry to the zip file. i...
...file, firefox would not be able to read it properly. zw.addentryfile(saveinzipas, ci.nsizipwriter.compression_none, filetoaddtozip, false); this example creates a folder in the zip called "sub folder" and then adds "c:\add this file.txt" to it, but it will be called "blah.txt". amodtime the modification time of the entry in microseconds. aqueue if true, the operation is queued for later
execution. if false, the operation is performed immediately. will be performed when processqueue() is called. exceptions thrown ns_error_not_initialized no zip file is open. ns_error_file_already_exists the specified path already exists in the zip file. ns_error_in_progress the zip writer is already performing another operation. addentryfile() adds a new file or directory to the zip file. if t...
...And 2 more matches
Break on DOM mutation - Firefox Developer Tools
a dom mutation breakpoint pauses the code when the dom node on which you have set the breakpoint is modified. you set a dom mutation breakpoint in the page inspector. navigate to the dom node in which you are interested and use the context menu to set the breakpoint. there are three choices: subtree modification
execution pauses if any of the elementʼs descendant nodes are modified. ...
...kpoint pauses the code when the dom node on which you have set the breakpoint is modified. you set a dom mutation breakpoint in the page inspector. navigate to the dom node in which you are interested and use the context menu to set the breakpoint. there are three choices: subtree modification
execution pauses if any of the elementʼs descendant nodes are modified. ...
...are modified. that means, the script
execution is stopped whenever a child node or descendant node deeper in the dom structure is added to or removed from the element the option is set on. examples for when this breakpoint is triggered are calling node.appendchild() and node.removechild(), calling childnode.remove() or setting element.innerhtml on one of the subnodes. attribute modification
execution pauses when any of the elementsʼ attributes are modified. that means, the script
execution is stopped whenever an attribute is added to or removed from the element the option is set on or the value of one of its attributes is changed. examples for when this breakpoint is triggered are calling element.setattribute(), element.removeattribute(), and element.classlist.add(), or setting element.i...
...And 2 more matches
Set a logpoint - Firefox Developer Tools
to create a logpoint: right click on a line number in the debugger panel and pick add log action from the context menu. create an expression inline. the result is logged in the console panel every time the line with the logpoint executes. ...
... to create a logpoint: right click on a line number in the debugger panel and pick add log action from the context menu. create an expression inline. the result is logged in the console panel every time the line with the logpoint executes. ...
... to create a logpoint: right click on a line number in the debugger panel and pick add log action from the context menu. create an expression inline. the result is logged in the console panel every time the line with the logpoint executes. ...
...And 2 more matches
Debugger - Firefox Developer Tools
when given events occur in debuggee code. when one of the events described below occurs in debuggee code, the engine pauses the debuggee and calls the corresponding debugging handler on each debugger instance that is observing the debuggee. the handler functions receive the debugger instance as their this value. most handler functions can return a resumption value indicating how the debuggee’s
execution should proceed. on a new debugger instance, each of these properties is initially undefined. any value assigned to a debugging handler must be either a function or undefined; otherwise a typeerror is thrown. handler functions run in the same thread in which the event occurred. they run in the compartment to which they belong, not in a debuggee compartment. onnewscript(script,global) new c...
...n value is ignored. onnewpromise(promise) a new promise object, referenced by the debugger.object instance promise, has been allocated in the scope of the debuggees. the promise’s allocation stack can be obtained using the promiseallocationstack accessor property of the debugger.object instance promise. this handler method should return a resumption value specifying how the debuggee’s
execution should proceed. however, note that a { return:value } resumption value is treated like undefined (“continue normally”);value is ignored. onpromisesettled(promise) a promise object, referenced by the debugger.object instance promise that was allocated within a debuggee scope, has settled (either fulfilled or rejected). the promise’s state, fulfillment or rejection value, and the alloca...
...r.object instance promise that was allocated within a debuggee scope, has settled (either fulfilled or rejected). the promise’s state, fulfillment or rejection value, and the allocation and resolution stacks can be obtained using the promise-related accessor properties of the debugger.object instance promise. this handler method should return a resumption value specifying how the debuggee’s
execution should proceed. however, note that a { return:value } resumption value is treated like undefined (“continue normally”);value is ignored. ondebuggerstatement(frame) debuggee code has executed adebugger statement inframe. this method should return a resumption value specifying how the debuggee’s
execution should proceed. onenterframe(frame) the stack frameframe is about to begin execu...
...And 2 more matches
Index - Firefox Developer Tools
property viewer lets you inspect the properties of the dom as an expandable tree structure, starting from the window object of the current page or the selected iframe. 17 debugger-api debugger, intermediate, intro, javascript, tools mozilla’s javascript engine, spidermonkey, provides a debugging interface named debugger which lets javascript code observe and manipulate the
execution of other javascript code. both firefox’s built-in developer tools and the firebug add-on use debugger to implement their javascript debuggers. however, debugger is quite general, and can be used to implement other kinds of tools like tracers, coverage analysis, patch-and-continue, and so on. 18 debugger when called as a constructor, the debugger object creates a new debugg...
...h debugger.object instance representing a debuggee function has an environment object representing the environment the function has closed over. 20 debugger.frame a debugger.frame instance represents a visible stack frame. given a debugger.frame instance, you can find the script the frame is executing, walk the stack to older frames, find the lexical environment in which the
execution is taking place, and so on. 21 debugger.memory the debugger api can help tools observe the debuggee’s memory use in various ways: 22 debugger.object a debugger.object instance represents an object in the debuggee, providing reflection-oriented methods to inspect and modify its referent. the referent’s properties do not appear directly as properties ...
...e: when the program reaches that line, the debugger pauses. a conditional breakpoint also has a condition associated with it, which is represented as an expression. when the program reaches the line, the debugger pauses only if the breakpoint's specified expression evaluates to true. 130 set watch expressions when debugging code, sometimes it's useful to watch expressions as
executions are paused. the debugger features a pane for entering expressions to be watched (watch expressions). as you step through code, the debugger will watch the expression and return any results. 131 step through code debugger, devtools, javascript, step through code when the debugger is stopped at a breakpoint, you can step through it using four buttons in the toolbar: 132...
...And 2 more matches
this - JavaScript
a function's this keyword behaves a little differently in javascript compared to other languages. it also has some differences between strict mode and non-strict mode. in most cases, the value of this is determined by how a function is called (runtime binding). it can't be set by assignment during
execution, and it may be different each time the function is called. es5 introduced the bind() method to set the value of a function's this regardless of how it's called, and es2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-exam...
...5 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax this value a property of an
execution context (global, function or eval) that, in non–strict mode, is always a reference to an object and in strict mode can be any value. description global context in the global
execution context (outside of any function), this refers to the global object whether in strict mode or not. // in web browsers, the window object is also the global object: console.log(this === window); // true a = 37...
...s on how the function is called. since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. function f1() { return this; } // in a browser: f1() === window; // true // in node: f1() === globalthis; // true in strict mode, however, if the value of this is not set when entering an
execution context, it remains as undefined, as shown in the following example: function f2() { 'use strict'; // see strict mode return this; } f2() === undefined; // true in the second example, this should be undefined, because f2 was called directly and not as a method or property of an object (e.g. window.f2()). this feature wasn't implemented in some browsers when they first started to support s...
...And 2 more matches
Venkman Introduction - Archive of obsolete content
rocedures, and tips described here will make you a more confident web developer and debugger. venkman is both a graphic and a console debugger. features such as breakpoint management, call stack inspection, and variable/object inspection are available from the user interface and from console commands, letting you work in the way you are most accustomed to. the interactive console also allows for
execution of arbitrary javascript code. venkman's keyboard shortcuts are the same as leading visual debugging environments, and gdb users should be familiar with venkman's /break, /step, /next, /finish, /frame, and /where commands. on windows, the javascript debugger compares favorably with visual interdev and other large web development tools. on other platforms, including mac os and unix, it is alone in...
...nterface toolbar the toolbar is located at the top of the debugger. the toolbar contains icons for stop, continue, step over, step into, step out, profile, and pretty print commands. ...
...top when the next line of javascript is executed, and the profile button, which can be used to measure
execution times for your scripts. when you enable profiling by clicking this button, a green checkmark appears next to the button and profile data for every function is collected, and can be saved by choosing save profile data as... from the profile menu. figure 4. stop button waiting for
execution also note that when you are currently executing javascript and click the stop button, the javascript stops immediately. if you are not running javascript and click the stop button, it will display "...", as in the figure 4, to indicate that the debugger will stop at the next instruction, but doesn't have anywhere to stop yet. this quick stop mode reflects a common scenario in javascript debugg...
...ext from the interactive session view. if you would like to keep venkman from stopping in a particular stack frame in the future, check "don't debug" from the stack frame's context menu. source code view the source code view is a read-only file viewer. files and specific functions within them can be displayed by selecting the appropriate file or function name in the script view. when script
execution is interrupted by the debugger, the line of the file where the interruption occurred is automatically displayed in the source code view. the line in question will be highlighted in yellow to make it easy to spot. clicking in the left margin of this view will set a breakpoint at that line. if the breakpoint is successfully set, the margin will show the letter "b" on a red background, and both the...
Sqlite.jsm
sion statement. tableexists(name) this function determines whether a table exists in the current database. it returns a promise that is resolved with a boolean indicating whether the table exists. indexexists(name) this functions determines whether a named index exists in the current database. it returns a promise that is resolved with a boolean indicating whether the index exists. statement
execution these apis facilitate
execution of statements on the connection. these are arguably the most important apis in this type. executecached(sql, params, onrow) execute(sql, params, onrow) these similar functions are used to execute a single sql statement on the connection. as you might have guessed by the name, there are 2 flavors: cached and non-cached. other than that, they behave identically. ...
... functions receive the following arguments: sql (required) string sql statement to execute. the trailing semicolon is not required. params (optional) parameters to bind to this statement. this can be an array or an object. see notes below. onrow (optional) function that is called when a row has been received. the return value is a promise that is resolved when the statement has finished
execution. when a statement is executed via executecached(), the prepared statement object is cached inside the opened connection. the next time this same sql statement is executed (the sql argument is identical to one passed in before), the old statement object is reused. this saves time associated with parsing the sql statement and creating a new statement object. the downside is the cached statement ob...
...rgument is identical to one passed in before), the old statement object is reused. this saves time associated with parsing the sql statement and creating a new statement object. the downside is the cached statement object lingers in the opened connection, taking up memory. when a statement is executed via execute(), the underlying statement object is thrown away as soon as the statement finishes
execution. executecached() is recommended for statements that will be executed many times. execute() is recommended for statements that will be executed seldomly or once. please note that callers don't need to prepare statements manually before
execution. just call executecached() and the statement will be prepared for you automatically. parameters can be bound to the statement by defining the params ar...
...ations for select statements. if your select statement could return lots of data, this buffering of returned rows could result in excessive memory usage. therefore, it's recommended to use onrow with select statements. along with a result row, onrow is passed a cancel function as its second argument. consumers of this api can call the cancel function should they want to immediately abort the
execution of the statement. when cancelled, subsequent rows will not be processed and no more onrow invocations will be made. if an exception is thrown by the onrow handler, the exception is logged and processing of subsequent rows occurs as if nothing happened. the promise is still resolved (not rejected). the return promise will be rejected with an error instance if the statement did not finish execu...
Tracing JIT
the jstracer component consists of a monitor and a recorder. the monitor watches the executing spidermonkey interpreter. when the monitor determines that the interpreter has entered a region of code that would benefit from native compilation, the monitor activates the recorder. the recorder records the activity of the interpreter, using nanojit to build an efficient, native representation of the
execution called a fragment. the monitor then calls into the native code stored in the fragment. a schematic diagram of the components of the tracing jit follows: generic low level component: nanojit/* the files in the nanojit directory define the nanojit component. nanojit/lir.* the nanojit/lir.cpp and nanojit/lir.h files define the intermediate representation lir, which is used as input to nanoji...
...g mode. this mode is relatively simple compared to recording mode. first the monitor allocates a native stack for the trace to use, and a state structure containing various key pointers into the spidermonkey interpreter's state, including a pointer to the native stack. it then imports the set of jsval values from the spidermonkey interpreter that the trace is known to read or write during its
execution. this set was determined during recording, and the imported values are stored locally within the native stack during
execution. the monitor then calls into the native code of the trace, passing in a pointer to the state structure as the sole argument. the native code of the trace runs, modifying the state structure and native stack, as well as calling native spidermonkey c functions, and readin...
...ding still hold. if guard's condition fails to hold, the guard either jumps to an exit or, if the guard has been extended, jumps to a sub-trace that has been recorded under the opposite assumption as the guard was checking. for example, when recording any conditional branch in the spidermonkey bytecode, a guard will be incorported into the trace that checks the branch is taken the same way during
execution as it was during recording. if this guard fails once, the trace will exit. if it fails enough times to become hot, the monitor will record an alternative sub-trace beginning at the guard and patch the code into the existing guard. thereafter, when the guard fails it will jump to the specialized sub-trace. the term bail denotes "exiting a trace due to to a failed guard". when a guard bails, it me...
...ey c function that gets part-way through executing and then forces a trace-exit (possibly due to a nested c function depending on not-yet-flushed state in the trace). a deep bail is special only insofar as it requires flushing the full set of deferred writes in the trace if it occurs (and further, requires that all registers holding temporary trace operands have flushed to the native stack before
execution). bailing from a regular guard involves executing precise per-guard write-flushing code, as the guard encodes a specific failed condition on a specific set of operands, and so the exit code can be much more fine-grained about and reconstructing the pre-bail state. a deep bail must be conservative because it is forced by the failure of an unknown condition elsewhere in native spidermonkey c code. ...
Set a breakpoint - Firefox Developer Tools
at this point you can do useful things like studying the value of different variables at that point, allowing you to work out why a problem is occurring. ...
...e source pane, you can handle setting breakpoints by bringing up the context menu over a line number. there are a few options available here: add breakpoint: add a standard unconditional breakpoint at this line number (see below). add condition: add a condition and create a conditional breakpoint (see below). add log: add a log point, which logs a value to your console rather than pausing
execution as a breakpoint does. continue to here: when stepping through code, this option tells the debugging to continue
execution through to this point. unconditional breakpoints an unconditional breakpoint is one where the code will always pause
execution when it is reached. you can set an unconditional breakpoint using the context menu (see above), or by: clicking on the line number for the line...
...in addition, if the line contains multiple function calls, each one will be given a small blue arrow icon to the left of it. these are called column breakpoints, and allow you to set the breakpoint to happen exactly on any one of the function calls in the line (or multiple calls), by clicking on each relevant one. conditional breakpoints a conditional breakpoint is one where the code will pause
execution when it is reached, only if a certain condition is met, such a variable having a certain value at the time. you can set a conditional breakpoint using the context menu (see above), or by highlighting the line you want to break at in the source pane and pressing ctrl + shift + b (windows/linux) or cmd + shift + b (macos). when you first choose to set a conditional breakpoint, a text entry line wi...
... change the previously set condition. inline variable preview new in firefox 71, the source pane now gives you an inline preview of the variables on each line of code you've stepped through: this is a very useful timesaver when stepping through your code. previously you’d have to scroll through the scopes panel to find variable values, or hover over a variable in the source pane. now when
execution pauses, you can view relevant variables immediately. note: there is also a new option in the context menu for the actual code in the source pane — hide inline preview/show inline preview — which allows you to turn the inline variables on/off. ...
UI Tour - Firefox Developer Tools
le currently loaded. when the source pane is focused you can search for a string in the file using ctrl + f (cmd + f on a mac). breakpoints have a blue arrow overlaid on the line number. conditional breakpoints have an orange arrow. if you're stopped at a breakpoint, the entire line gets a green overlay. in the screenshot below there are three breakpoints: line 82 has a normal breakpoint and
execution is paused here line 85 has a logpoint which logs the contents of tablerow to the console line 100 has a conditional breakpoint the third column shows more information about the breakpoints. for example, the logpoint at line 85 logs the value of the tablerow variable to the console and the conditional breakpoint at line 100 breaks if the contents of the todolist is undefined. toolbar at th...
...oints. for example, the logpoint at line 85 logs the value of the tablerow variable to the console and the conditional breakpoint at line 100 breaks if the contents of the todolist is undefined. toolbar at the top of the right-hand pane, there's a toolbar: the toolbar consists of: four buttons to control the debugger's movement through the script: play/pause (f8): pauses or resumes
execution of the script you're debugging. when it displays a "play" icon, that means the script is paused, either because you've paused it with this button or because you've hit a breakpoint. step over (f10): steps to the next line of javascript code. step in (f11): steps into the function call on the current line of javascript code. step out (shift-f11): runs the script until the current function...
... and map them to the generated ones loaded in a page, to ease debugging of translformed sources. see use a source map for details. breakpoints list under the toolbar, you'll see all the breakpoints you've set. next to each breakpoint is a checkbox which you can use to enable/disable it: watch expressions you can add watch expressions in the right pane. they will be evaluated when code
execution is paused: variable tooltip hover on a variable show a tooltip with its value inside: call stack when the debugger's paused, you'll see a call stack: each level of the call stack gets a line, with the name of the function and the filename and line number. clicking a line selects the corresponding line in the source pane. note: if you click step over (f10) after changing the selected li...
... selects the corresponding line in the source pane. note: if you click step over (f10) after changing the selected line in the source pane, the debugger executes until reaching the line following the newly-selected line (disregarding whatever line the debugger originally stopped at). right-clicking in the call stack pane opens a context menu with the following items: restart frame restarts
execution at the beginning of the current frame. enable framework grouping collects items belonging to a framework into a collapsible group (for example, jquery in the screenshot above). when grouping is enabled, the menu option changes to disable framework grouping. copy source uri copies the full identifier of the source file to the clipboard. ignore source causes the debugger to skip the file when "s...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
ction is not passed any arguments, and no return value is expected. code an optional syntax allows you to include a string instead of a function, which is compiled and executed every delay milliseconds. this syntax is not recommended for the same reasons that make using eval() a security risk. delayoptional the time, in milliseconds (thousandths of a second), the timer should delay in between
executions of the specified function or code. see delay restrictions below for details on the permitted range of delay values. arg1, ..., argn optional additional arguments which are passed through to the function specified by func once the timer expires. note: passing additional arguments to setinterval() in the first syntax does not work in internet explorer 9 and earlier. if you want to enable this...
... in gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2), intervals are clamped to fire no more often than once per second in inactive tabs. the "this" problem when you pass a method to setinterval() or any other function, it is invoked with the wrong this value. this problem is explained in detail in the javascript reference. explanation code executed by setinterval() runs in a separate
execution context than the function from which it was called. as a consequence, the this keyword for the called function is set to the window (or global) object, it is not the same as the this value for the function that called settimeout. see the following example (which uses settimeout() instead of setinterval() – the problem, in fact, is the same for both timers): myarray = ['zero', 'one', 'two']; m...
...al() will be pinned to 4 ms. browsers may enforce even more stringent minimum values for the interval under some circumstances, although these should not be common. note also that the actual amount of time that elapses between calls to the callback may be longer than the given delay; see reasons for delays longer than specified in windoworworkerglobalscope.settimeout() for examples. ensure that
execution duration is shorter than interval frequency if there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using settimeout(). for example, if using setinterval() to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from co...
...urn in order. in these cases, a recursive settimeout() pattern is preferred: (function loop(){ settimeout(function() { // your logic here loop(); }, delay); })(); in the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside settimeout() after the logic has completed executing. while this pattern does not guarantee
execution on a fixed interval, it does guarantee that the previous interval has completed before recursing. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.setinterval()' in that specification. living standard method moved to the windoworworkerglobalscope mixin in the latest spec. html living standardthe d...
Loops and iteration - JavaScript
ement the do...while statement repeats until a specified condition evaluates to false. a do...while statement looks as follows: do statement while (condition); statement is always executed once before the condition is checked. (to execute multiple statements, use a block statement ({ ... }) to group those statements.) if condition is true, the statement executes again. at the end of every
execution, the condition is checked. when the condition is false,
execution stops, and control passes to the statement following do...while. example in the following example, the do loop iterates at least once and reiterates until i is no longer less than 5. let i = 0; do { i += 1; console.log(i); } while (i < 5); while statement a while statement executes its statements as long as a specified con...
...es to true. a while statement looks as follows: while (condition) statement if the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop. the condition test occurs before statement in the loop is executed. if the condition returns true, statement is executed and the condition is tested again. if the condition returns false,
execution stops, and control is passed to the statement following while. to execute multiple statements, use a block statement ({ ... }) to group those statements. example 1 the following while loop iterates as long as n is less than 3: let n = 0; let x = 0; while (n < 3) { n++; x += n; } with each iteration, the loop increments n and adds that value to x. therefore, x and n take on the following...
...condition never becomes false: // infinite loops are bad! while (true) { console.log('hello, world!'); } labeled statement a label provides a statement with an identifier that lets you refer to it elsewhere in your program. for example, you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its
execution. the syntax of the labeled statement looks like the following: label : statement the value of label may be any javascript identifier that is not a reserved word. the statement that you identify with a label may be any statement. example in this example, the label markloop identifies a while loop. markloop: while (themark === true) { dosomething(); } break statement use the break st...
... ' + z); z += 1; if (z === 10 && x === 10) { break labelcancelloops; } else if (z === 10) { break; } } } continue statement the continue statement can be used to restart a while, do-while, for, or label statement. when you use continue without a label, it terminates the current iteration of the innermost enclosing while, do-while, or for statement and continues
execution of the loop with the next iteration. in contrast to the break statement, continue does not terminate the
execution of the loop entirely. in a while loop, it jumps back to the condition. in a for loop, it jumps to the increment-expression. when you use continue with a label, it applies to the looping statement identified with that label. the syntax of the continue statement looks like the follo...
await - JavaScript
the await operator is used to wait for a promise. it can only be used inside an async function. syntax [rv] = await expression; expression a promise or any value to wait for. rv returns the fulfilled value of the promise, or the value itself if it's not a promise. ...
... wait for a promise. it can only be used inside an async function. syntax [rv] = await expression; expression a promise or any value to wait for. rv returns the fulfilled value of the promise, or the value itself if it's not a promise. description the await expression causes async function
execution to pause until a promise is settled (that is, fulfilled or rejected), and to resume
execution of the async function after fulfillment. ...
...tled (that is, fulfilled or rejected), and to resume
execution of the async function after fulfillment. when resumed, the value of the await expression is that of the fulfilled promise. if the promise is rejected, the await expression throws the rejected value. if the value of the expression following the await operator is not a promise, it's converted to a resolved promise. an await can split
execution flow, allowing the caller of the await's function to resume
execution before the deferred continuation of the await's function. ...
...lue. if the value of the expression following the await operator is not a promise, it's converted to a resolved promise. an await can split
execution flow, allowing the caller of the await's function to resume
execution before the deferred continuation of the await's function. after the await defers the continuation of its function, if this is the first await executed by the function, immediate
execution also continues by returning to the function's caller a pending promise for the completion of the await's function and resuming
execution of that caller. examples awaiting a promise to be fulfilled if a promise is passed to an await expression, it waits for the promise to be fulfilled and returns the fulfilled value. function resolveafter2seconds(x) { return new promise(resolve => { sett...
yield - JavaScript
interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax [rv] = yield [expression] expression optional defines the value to return from the generator function via the iterator protocol. if omitted, undefined is returned instead. rv optional retrieves the optional value passed to the generator's next() method to resume its
execution. description the yield keyword pauses generator function
execution and the value of the expression following the yield keyword is returned to the generator's caller. it can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it. it cannot be called from nested functions or from callbacks. the yield ke...
...be called from nested functions or from callbacks. the yield keyword causes the call to the generator's next() method to return an iteratorresult object with two properties: value and done. the value property is the result of evaluating the yield expression, and done is false, indicating that the generator function has not fully completed. once paused on a yield expression, the generator's code
execution remains paused until the generator's next() method is called. each time the generator's next() method is called, the generator resumes
execution, and runs until it reaches one of the following: a yield, which causes the generator to once again pause and return the generator's new value. the next time next() is called,
execution resumes with the statement immediately after the yield. throw is ...
...led. each time the generator's next() method is called, the generator resumes
execution, and runs until it reaches one of the following: a yield, which causes the generator to once again pause and return the generator's new value. the next time next() is called,
execution resumes with the statement immediately after the yield. throw is used to throw an exception from the generator. this halts
execution of the generator entirely, and
execution resumes in the caller (as is normally the case when an exception is thrown). the end of the generator function is reached. in this case,
execution of the generator ends and an iteratorresult is returned to the caller in which the value is undefined and done is true. ...
... if an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation. ...
async function - JavaScript
control returns from p1. async function foo() { const p1 = new promise((resolve) => settimeout(() => resolve('1'), 1000)) const p2 = new promise((_,reject) => settimeout(() => reject('2'), 500)) const results = [await p1, await p2] // do not do this! use promise.all or promise.allsettled instead. } foo().catch(() => {}) // attempt to swallow all errors... ...
...(function() { resolve("slow") console.log("slow promise is done") }, 2000) }) } function resolveafter1second() { console.log("starting fast promise") return new promise(resolve => { settimeout(function() { resolve("fast") console.log("fast promise is done") }, 1000) }) } async function sequentialstart() { console.log('==sequential start==') // 1.
execution gets here almost instantly const slow = await resolveafter2seconds() console.log(slow) // 2. this runs 2 seconds after 1. const fast = await resolveafter1second() console.log(fast) // 3. this runs 3 seconds after 1. } async function concurrentstart() { console.log('==concurrent start with await=='); const slow = resolveafter2seconds() // starts timer immediately const fast = resol...
...veafter2seconds() console.log(slow) // 2. this runs 2 seconds after 1. const fast = await resolveafter1second() console.log(fast) // 3. this runs 3 seconds after 1. } async function concurrentstart() { console.log('==concurrent start with await=='); const slow = resolveafter2seconds() // starts timer immediately const fast = resolveafter1second() // starts timer immediately // 1.
execution gets here almost instantly console.log(await slow) // 2. this runs 2 seconds after 1. console.log(await fast) // 3. this runs 2 seconds after 1., immediately after 2., since fast is already resolved } function concurrentpromise() { console.log('==concurrent start with promise.all==') return promise.all([resolveafter2seconds(), resolveafter1second()]).then((messages) => { console.log(...
...the second timer is not created until the first has already fired, so the code finishes after 3 seconds. in concurrentstart, both timers are created and then awaited. the timers run concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer. however, the await calls still ru...
Appendix D: Loading Scripts - Archive of obsolete content
pports firebug based sandboxes. examples the following code will execute a simple script in a sandbox with the privilege level of the current content page. the globals of the current content window will be available in the scripts global scope. in stack traces, the script will appear to have been loaded from the file "zz-9://plural/zed/alpha", line 42. // use the current content window as the
execution context. // to make properties defined by scripts executing on the page // available to your sandbox script, use content.wrappedjsobject // instead. let context = content; // create the sandbox let sandbox = components.utils.sandbox(context, { // make properties of the context object available via the // script's global scope sandboxprototype: context, // wrap objects retrieved f...
...space, they have no direct access to the dom or window properties of windows or documents, and therefore must often pass around references to these objects and any document-specific state data that they require. examples the following code will import a module into the current global scope. all variables named in the target script's exported_symbols global array will be copied into the current
execution context. components.utils.import("resource://my-package/my-module.jsm"); the following function will import an arbitrary module into a singleton object, which it returns. if the argument is not an absolute path, the module is imported relative to the caller's filename. function module(uri) { if (!/^[a-z-]+:/.exec(uri)) uri = /([^ ]+\/)[^\/]+$/.exec(components.stack.caller.filename...
...nterfering with the main thread. they may safely perform synchronous xmlhttprequests or other intensive computation which would normally need to be broken up into multiple callbacks. safety: as workers have no access to objects which might cause a crash or deadlock when executed re-entrantly or by spinning the event loop, there are significant safety advantages over other methods of asynchronous
execution. disadvantages limited scoping: as data from the main thread may only be accessed via json message passing, there are significant difficulties in performing many operations in worker scopes. dom access: as there is no dom access in worker scopes, xmlhttprequests may not easily be used with xml or html sources, and should instead only be used with json or other text-based sources. debugging...
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
however, the concept can be a little confusing at first. conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. ...
...however, the concept can be a little confusing at first. conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. ...
...o write the code for it to work. now, let's see what happens when we call the function before we write it: catname("chloe"); function catname(name) { console.log("my cat's name is " + name); } /* the result of the code above is: "my cat's name is chloe" */ even though we call the function in our code first, before the function is written, the code still works. this is because of how context
execution works in javascript. hoisting works well with other data types and variables. the variables can be initialized and used before they are declared. only declarations are hoisted javascript only hoists declarations, not initializations. if a variable is declared and initialized after using it, the value will be undefined. for example: console.log(num); // returns undefined, as only declaration w...
Choosing the right approach - Learn web development
the interval will be the same regardless of how long the code takes to run. with setinterval(), the interval we choose includes the time taken to execute the code we want to run in. let's say that the code takes 40 milliseconds to run — the interval then ends up being only 60 milliseconds. when your code has the potenti...
...al(), the interval we choose includes the time taken to execute the code we want to run in. let's say that the code takes 40 milliseconds to run — the interval then ends up being only 60 milliseconds. when your code has the potential to take longer to run than the time interval you’ve assigned, it’s better to use recursive settimeout() — this will keep the time interval constant between
executions regardless of how long the code takes to execute, and you won't get errors. browser compatibility desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetsettimeoutchrome full support 30edge full support 12...
... compatibility unknown compatibility unknownsee implementation notes.see implementation notes. further information cooperative asynchronous javascript: timeouts and intervals, in particular settimeout() settimeout() reference setinterval() setinterval() is a method that allows you to run a function repeatedly with a set interval of time between each
execution. not as efficient as requestanimationframe(), but allows you to choose a running rate/frame rate. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no yes no (unless it is the same one) no code example the following function creates a new date() object, extracts a time string out...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
ecify a value of 0 (or simply omit the value), the function will run as soon as possible. (see the note below on why it runs "as soon as possible" and not "immediately".) more on why you might want to do this later. zero or more values that represent any parameters you want to pass to the function when it is run. note: the specified amount of time (or the delay) is not the guaranteed time to
execution, but rather the minimum time to
execution. the callbacks you pass to these functions cannot run until the stack on the main thread is empty. as a consequence, code like settimeout(fn, 0) will execute as soon as the stack is empty, not immediately. if you execute code like settimeout(fn, 0) but then immediately after run a loop that counts from 1 to 10 billion, your callback will be executed afte...
......
...n can calculate a different delay before running the next iteration. in other words, the value of the second parameter can specify a different time in milliseconds to wait before running the code again. when your code has the potential to take longer to run than the time interval you’ve assigned, it’s better to use recursive settimeout() — this will keep the time interval constant between
executions regardless of how long the code takes to execute, and you won't get errors. immediate timeouts using 0 as the value for settimeout() schedules the
execution of the specified callback function as soon as possible but only after the main code thread has been run. for instance, the code below (see it live) outputs an alert containing "hello", then an alert containing "world" as soon as you click...
How Mozilla's build system works
ling the build system what to do. during build backend generation, all moz.build files relevant to the current build configuration are read and converted into files and actions used to build the tree (such as makefiles). in this section, we'll talk about how moz.build files actually work. an individual moz.build file is actually a python script. however, they are unlike most python scripts. the
execution environment is strictly controlled, so moz.build files can only perform a limited set of operations. moz.build files are limited to performing the following actions: calling functions that are explicitly made available to the moz.build environment. assigning to a well-defined set of variables whose name is uppercase. creating new variables whose name is not uppercase (this includes defining ...
...able to the moz.build environment. assigning to a well-defined set of variables whose name is uppercase. creating new variables whose name is not uppercase (this includes defining functions). moz.build files cannot do the following: import modules. open files. use the print statement or function. reference many of python's built-in or global functions (they are not made available to the
execution environment). the most important actions of moz.build files are #1 and #2 from the above list. these are how the
execution of a moz.build file tells the build system what to do. for example, you can assign to the dirs list to define which directories to traverse into looking for additional moz.build files. the output of the
execution of an individual moz.build file is a python dictionary. this...
...this is what we were referring to when we said you can think of moz.build files as data structures. ...
HTML parser threading
ted ops are destructed and the rest are left in the queue.) the last op in the queue may be an op for attempting to execute a script that may block the parser (ops for attempting to execute async and defer scripts are normal tree ops and don't need to be the last op in a queue). ...
...ue). the parts of the parser that drive the tokenizer/tree builder pairs guarantee to flush tree ops immediately if a script
execution tree op is generated. (the tree builder makes the tokenizer return immediately when such an op is generated.) thus, a tree op that may cause the parser to block can only occur as the last op in a queue that runflushloop sees. preparing the parser thread for script
execution when the parser thread sees that it has generated a tree op that attempts to execute a (non-async, non-defer) script, it starts speculating. it acquires mspeculationmutex and while holding it, it creates a new speculation and adds it to the queue of speculations, flushes the tree ops to the main thread, marks the nshtml5streamparser as being in a speculating state and sets the newly created specu...
...he tree ops aren't used and it's mostly harmless if the speculative loads are wrong. after an external script finishes executing, it dispatches an event to reflush the tree op executor. the reflush causes a call to nshtml5parser::parseuntilblocked(). parseuntilblocked() parses data left by document.write() in the linked list of buffers, because the parser was blocked. this might cause more script
execution tree ops to be generated and executed and document.write() to be called more times. when parseuntilblocked() exhausts the data available to it, it calls nshtml5streamparser::continueafterscripts to resume the consumption of data from the network. continuing to use network-originating data after scripts nshtml5streamparser::continueafterscripts runs on the main thread. it acquires mspeculationmute...
Logging
gging purposes. you can select events to be logged by module or level. a module is a user-defined class of log events. a level is a numeric value that indicates the seriousness of the event to be logged. you can combine module and level criteria to get highly selective logging. nspr also provides "assert"-style macros and functions to aid in application debugging. conditional compilation and
execution log types and variables logging functions and macros use example conditional compilation and
execution nspr's logging facility is conditionally compiled in and enabled for applications using it. these controls are platform dependent. logging is not compiled in for the win16 platform. logging is compiled into the nspr debug builds; logging is not compiled into the nspr optimized builds. the ...
...ogging is compiled into the nspr debug builds; logging is not compiled into the nspr optimized builds. the compile time #define values debug or force_pr_log enable nspr logging for application programs. to enable nspr logging and/or the debugging aids in your application, compile using the nspr debug build headers and runtime. set one of the compile-time defines when you build your application.
execution-time control of nspr's logging uses two environment variables. these variables control which modules and levels are logged as well as the file name of the log file. by default, no logging is enabled at
execution time. log types and variables two types supporting nspr logging are exposed in the api: prlogmoduleinfo prlogmodulelevel two environment variables control the behavior of logging ...
...me control of nspr's logging uses two environment variables. these variables control which modules and levels are logged as well as the file name of the log file. by default, no logging is enabled at
execution time. ...
Threads
threads are critical resources and therefore require some management. ...
...threads are critical resources and therefore require some management. ...
... the basic nspr threading api. threading types and constants threading functions a thread has a limited number of resources that it truly owns. these resources include a stack and the cpu registers (including pc). to an nspr client, a thread is represented by a pointer to an opaque structure of type prthread. a thread is created by an explicit client request and remains a valid, independent
execution entity until it returns from its root function or the process abnormally terminates. threads are critical resources and therefore require some management. to synchronize the termination of a thread, you can join it with another thread (see pr_jointhread). joining a thread provides definitive proof that the target thread has terminated and has finished with both the resources to which the thread h...
Rhino scopes and contexts
o understand the distinction between contexts and scopes. both are required to execute scripts, but they play different roles. simple embeddings of rhino probably won't need any of the information here, but more complicated embeddings can gain performance and flexibility from the techniques described below. ...
...that context will be returned and an internal counter incremented. ...
...se calls will work properly even if there is already a context associated with the current thread. that context will be returned and an internal counter incremented. only when the counter reaches zero will it be disassociated from the thread. remember to put the exit() call in a finally block if you're executing code that could throw an exception. scopes a scope is a set of javascript objects.
execution of scripts requires a scope for top-level script variable storage as well as a place to find standard objects like function and object. it's important to understand that a scope is independent of the context that created it. you can create a scope using one context and then evaluate a script using that scope and another context (either by exiting the current context and entering another, or by e...
JSAPI User Guide
fmemory(cx); return false; } this does something subtly different from what js_reporterror does. most errors, including those raised by js_reporterror, are represented as javascript exceptions and thus interact with the javascript exception-handling language features, try, catch, and finally. however, in some cases we do not want scripts to be able to catch an error; we want script
execution to terminate right away. if the system runs out of memory in the middle of a script, we do not want finally blocks to execute, because almost anything a script does requires at least a little memory, and we have none. if a script has been running too long and we want to kill it, it's no good to throw an exception—the script could just catch it and keep going. therefore js_reportoutofmemory(cx)...
... or 2.) compile the script once with a call to js_compilescript or js_compileucscript, and then execute it repeatedly with individual calls to js_executescript. the "uc" versions of these calls provide support for unicode-encoded scripts. an object you create using a script only can be made available only during the lifetime of the script, or can be created to persist after the script completes
execution. ordinarily, once script
execution is complete, its objects are destroyed. in many cases, this behavior is just what your application needs. in other cases, however, you will want object persistence across scripts, or for the lifetime of your application. in these cases you need to embed object creation code directly in your application, or you need to tie the object directly to the global object...
...that the kind of attack we're talking about here is where a hacker uses javascript to attack the c++ code of the engine itself (or your embedding). the rest of the items in this list talk about security issues that arise within javascript itself, even if the engine is working properly. block simple denial-of-service attacks - a program like while(true){} should not hang your application. to stop
execution of scripts that run too long, use js_setoperationcallback. likewise, a function like function f(){f();} should not crash your application with a stack overflow. to block that, use js_setnativestackquota. control access to sensitive data - your application might expose data to some scripts that other scripts should not be able to see. for example, you might let your customers write scripts that o...
Debugger.Object - Firefox Developer Tools
omise has been fulfilled with. if the referent is not a promise, or the promise has not been fulfilled, throw a typeerror. promisereason return a debuggee value representing the value the promise has been rejected with. if the referent is not a promise, or the promise has not been rejected, throw a typeerror. promiseallocationsite if the referent is a promise, this is the javascript
execution stack captured at the time of the promise’s allocation. this can return null if the promise was not created from script. if the referent is not a promise, throw a typeerror exception. promiseresolutionsite if the referent is a promise, this is the javascript
execution stack captured at the time of the promise’s resolution. this can return null if the promise was not resolved by calling its ...
...whose scope the referent was allocated. this does not unwrap cross-compartment wrappers: if the referent is a wrapper, the result refers to the wrapper’s global, not the wrapped object’s global. the result refers to the global directly, not via a wrapper. allocationsite if object allocation site tracking was enabled when this debugger.object’s referent was allocated, return the javascript
execution stack captured at the time of the allocation. otherwise, return null. function properties of the debugger.object prototype the functions described below may only be called with a this value referring to a debugger.object instance; they may not be used as methods of other kinds of objects. the descriptions use “referent” to mean “the referent of this debugger.object instance”. unless o...
...ible to the given debuggee code and which refer to debugger-held debuggee values, and do so without mutating any existing debuggee environment. note that, like executeinglobal, any declarations it contains affect the referent global object, even ascode is evaluated in an environment extended according tobindings. (in the terms used by the ecmascript specification, the variableenvironment of the
execution context forcode is the referent, and thebindings appear in a new declarative environment, which is the eval code’s lexicalenvironment.) theoptions argument is as for debugger.frame.prototype.eval. asenvironment() if the referent is a global object, return the debugger.environment instance representing the referent’s global lexical scope. the global lexical scope’s enclosing scope is t...
Debugger.Object - Firefox Developer Tools
ll. this function follows the invocation function conventions. if the referent is not a global object, throw a typeerror exception. codeis interpreted as strict mode code when it contains a use strict directive. ifcode is not strict mode code, then variable declarations incode affect the referent global object. (in the terms used by the ecmascript specification, the variableenvironment of the
execution context for the eval code is the referent.) theoptions argument is as for debugger.frame.prototype.eval. evalinglobalwithbindings(code,bindings, [options]) like evalinglobal, but evaluatecode using the referent as the variable object, but with a lexical environment extended with bindings from the objectbindings. for each own enumerable property ofbindings namedname whose value isvalue, in...
...values, and do so without mutating any existing debuggee environment. note that, like evalinglobal, if the code passed to evalinglobalwithbindings is not strict mode code, then any declarations it contains affect the referent global object, even ascode is evaluated in an environment extended according tobindings. (in the terms used by the ecmascript specification, the variableenvironment of the
execution context for non-strict eval code is the referent, and thebindings appear in a new declarative environment, which is the eval code's lexicalenvironment.) theoptions argument is as for debugger.frame.prototype.eval. asenvironment() if the referent is a global object, return the debugger.environment instance representing the referent as a variable environment for evaluating code. if the refe...
... call to object.preventextensions. for all watchpoint handler methods: handler calls receive the handler object itself as the this value. theframe argument is the current stack frame, whose code is about to perform the operation on the object being reported. if the method returns undefined, then spidermonkey makes the announced change to the object, and continues
execution normally. if the method returns an object: if the object has a superseded property whose value is a true value, then spidermonkey does not make the announced change. if the object has a resume property, its value is taken as a resumption value, indicating how
execution should proceed. (however, return resumption values are not supported.) if a given method is absent fro...
Background Tasks API - Web APIs
s. certainly most if not all code that is capable of making changes to the dom is running in the main thread, since it's common for user interface changes to only be available to the main thread. because event handling and screen updates are two of the most obvious ways users notice performance issues, it's important for your code to be a good citizen of the web and help to prevent stalls in the
execution of the event loop. in the past, there's been no way to do this reliably other than by writing code that's as efficient as possible and by offloading as much work as possible to workers. window.requestidlecallback() makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use...
...tions to a queue, with an idle callback that runs those functions whenever the system is idle for long enough a time to make progress. variable declarations let tasklist = []; let totaltaskcount = 0; let currenttasknumber = 0; let taskhandle = null; these variables are used to manage the list of tasks that are waiting to be performed, as well as status information about the task queue and its
execution: tasklist is an array of objects, each representing one task waiting to be run. totaltaskcount is a counter of the number of tasks that have been added to the queue; it will only go up, never down. we use this to do the math to present progress as a precentage of total work to do. currenttasknumber is used to track how many tasks have been processed so far. taskhandle is a reference to the ...
...}; window.cancelidlecallback = window.cancelidlecallback || function(id) { cleartimeout(id); }; managing the task queue next, let's look at the way we manage the tasks that need to be performed. we're going to do this by creating a fifo queue of tasks, which we'll run as time allows during the idle callback period. enqueueing tasks first, we need a function that enqueues tasks for future
execution. that function, enqueuetask(), looks like this: function enqueuetask(taskhandler, taskdata) { tasklist.push({ handler: taskhandler, data: taskdata }); totaltaskcount++; if (!taskhandle) { taskhandle = requestidlecallback(runtaskqueue, { timeout: 1000 }); } schedulestatusrefresh(); } enqueuetask() accepts as input two parameters: taskhandler is a function which wil...
HTMLScriptElement - Web APIs
javascript files should be served with the application/javascript mime type, but browsers are lenient and block them only if the script is served with an image type (image/*), video type (video/*), audio type (audio/*), or text/csv. if the script is blocked, its element receives an error event; otherwise, it receives a load event. ...
...riptelement.charset is a domstring representing the character encoding of an external script. it reflects the charset attribute. htmlscriptelement.async htmlscriptelement.defer the async and defer attributes are boolean attributes that control how the script should be executed. the defer and async attributes must not be specified if the src attribute is absent. there are three possible
execution modes: if the async attribute is present, then the script will be executed asynchronously as soon as it downloads. if the async attribute is absent but the defer attribute is present, then the script is executed when the page has finished parsing. if neither attribute is present, then the script is fetched and executed immediately, blocking further parsing of the page. the defe...
...script> element (ignoring other nodes like comments) in tree order. on setting, it acts the same way as the textcontent idl attribute. note: when inserted using the document.write() method, <script> elements execute (typically synchronously), but when inserted using innerhtml or outerhtml, they do not execute at all. htmlscriptelement.nomodule is a boolean that if true, stops the script's
execution in browsers that support es2015 modules — used to run fallback scripts in older browsers that do not support javascript modules. htmlscriptelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use when fetching the script, and fetches done by that script. methods no specific methods; inherits methods from its parent, htmlelement...
Window - Web APIs
and eventtarget. window.alert() displays an alert dialog. window.blur() sets focus away from the window. window.cancelanimationframe() enables you to cancel a callback previously scheduled with window.requestanimationframe. window.cancelidlecallback() enables you to cancel a callback previously scheduled with window.requestidlecallback. window.clearimmediate() cancels the repeated
execution set using setimmediate. window.close() closes the current window. window.confirm() displays a dialog with a message that the user needs to respond to. window.dump() writes a message to the console. window.find() searches for a given string in a window. window.focus() sets focus on the current window. window.getcomputedstyle() gets computed style for the specified element. computed s...
... register an event handler to a specific event type on the window. eventtarget.dispatchevent() used to trigger an event. windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding. windoworworkerglobalscope.btoa() creates a base-64 encoded ascii string from a string of binary data. windoworworkerglobalscope.clearinterval() cancels the repeated
execution set using windoworworkerglobalscope.setinterval(). windoworworkerglobalscope.cleartimeout() cancels the delayed
execution set using windoworworkerglobalscope.settimeout(). windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap. optionally the source is cropped to the rectangle of pixels originating at ...
...onunhandledrejection an event handler for unhandled promise rejection events. windoweventhandlers.onunload called when the user navigates away from the page. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. error fired when a resource failed to load, or can't be used. for example, if a script has an
execution error or an image can't be found or is invalid. also available via the onerror property. languagechange fired at the global scope object when the user's preferred language changes. also available via the onlanguagechange property. orientationchange fired when the orientation of the device has changed. also available via the onorientationchange property. devicemotion fired at a regular in...
Grammar and types - JavaScript
racters, line terminators, comments, or whitespace. (spaces, tabs, and newline characters are considered whitespace.) comments the syntax of comments is the same as in c++ and in many other languages: // a one line comment /* this is a longer, * multi-line comment */ /* you can't, however, /* nest comments */ syntaxerror */ comments behave like whitespace, and are discarded during script
execution. note: you might also see a third type of comment syntax at the start of some javascript files, which looks something like this: #!/usr/bin/env node. this is called hashbang comment syntax, and is a special comment used to specify the path to a particular javascript engine that should execute the script. see hashbang comments for more details. declarations javascript has three kinds of vari...
...dentifiers. (for more details, see this blog post.) you can also use the unicode escape sequences as characters in identifiers. some examples of legal names are number_hits, temp99, $credit, and _name. declaring variables you can declare a variable in two ways: with the keyword var. for example, var x = 42. this syntax can be used to declare both local and global variables, depending on the
execution context. with the keyword const or let. for example, let y = 13. this syntax can be used to declare a block-scope local variable. (see variable scope below.) you can also simply assign a value to a variable for example, x = 42. this form creates an undeclared global variable. it also generates a strict javascript warning. undeclared global variables can often lead to unexpected behavior. thus,...
...e the other fundamental elements in the language. you can think of objects as named containers for values, and functions as procedures that your script can perform. data type conversion javascript is a dynamically typed language. this means you don't have to specify the data type of a variable when you declare it. it also means that data types are automatically converted as-needed during script
execution. so, for example, you could define a variable as follows: var answer = 42; and later, you could assign the same variable a string value, for example: answer = 'thanks for all the fish...'; because javascript is dynamically typed, this assignment does not cause an error message. numbers and the '+' operator in expressions involving numeric and string values with the + operator, javascript...
continue - JavaScript
in a for loop, it jumps to the update expression. ...
... in a for loop, it jumps to the update expression. ...
... the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax continue [label]; label identifier associated with the label of the statement. description in contrast to the break statement, continue does not terminate the
execution of the loop entirely: instead, in a while loop, it jumps back to the condition. in a for loop, it jumps to the update expression. the continue statement can include an optional label that allows the program to jump to the next iteration of a labeled loop statement instead of the current loop. in this case, the continue statement needs to be nested within this labeled statement. examples...
return - JavaScript
if specified, a given value is returned to the function caller. for example, the following function returns the square of its argument, x, where x is a number. ...
...example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax return [[expression]]; expression the expression whose value is to be returned. if omitted, undefined is returned instead. ...
...no line terminator is allowed between the return keyword and the expression. return a + b; is transformed by asi into: return; a + b; the console will warn "unreachable code after return statement". ...
/loader - Archive of obsolete content
etails. @loader/options this pseudo module exposes all the options that were used to configure this loader. it enables you to create new loader instances identical to the current one: let { loader } = require('toolkit/loader'); let options = require('@loader/options'); let loader = loader(options); this module is useful in very specific cases. for example the sdk uses this feature during test
execution to create an identical environment with a different state to test how specific modules handle unloads. @loader/unload this pseudo module exposes an object that is unique per loader instance. it is used as a subject for observer notification to allow use of the observer service for defining hooks reacting on the unload of a specific loader. the sdk builds a higher level api on top of this for ha...
...version of js used, defaults to '1.8'. // load script from the given location to a given sandbox: evaluate(sandbox, 'resource://path/to/script.js') // evaluate `code` as if it was from `foo/bar.js`: evaluate(sandbox, 'foo/bar.js', { source: code, version: '1.7' // you could also use other options described above. }) require() as already mentioned in loading modules it's common to start
execution by loading a main module. but sometimes you may want to prepare the environment using existing modules before doing that. in such cases you can create a requirer module instance and a version of require exposed to it with this function: let requirer = module(requirerid, requireruri); let require = require(loader, requirer); let boostrap = require(bootstrapid); resolveuri() this function is use...
frame/utils - Archive of obsolete content
module exports create function that takes the nsidomdocument of a privileged document and creates a browser element in its documentelement: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,foo'); let frame = create(window.document); optionally create can be passed set of options to configure created frame even further. ...
... string uri of the document to be loaded into the new frame. defaults to about:blank. remote boolean if true separate process will be used for this frame, and all the following options are ignored. allowauth boolean whether to allow auth dialogs. defaults to false. allowjavascript boolean whether to allow javascript
execution. defaults to false. allowplugins boolean whether to allow plugin
execution. defaults to false. returns frame : the new browser element. ...
lang/functional - Archive of obsolete content
wrapped function may be reused and does not need to be repeated each time. this also enables you to use these functions as event listeners. let { defer } = require("sdk/lang/functional"); let fn = defer(function myevent (event, value) { console.log(event + " : " + value); }); fn("click", "#home"); console.log("done"); // this will print 'done' before 'click : #home' since // we deferred the
execution of the wrapped `myevent` // function, making it non-blocking and executing on the // next event loop parameters fn : function the function to be deferred. returns function : the new, deferred function. remit() an alias for defer. invoke(callee, params, self) invokes callee, passing params as an argument and self as this. returns the value that is returned by callee. let { invoke } = req...
...u pass additional, optional, arguments, they will be forwarded on to the function when it is invoked. let { delay } = require("sdk/lang/functional"); delay(printadd, 2000, 5, 10); // prints "5+10=15" in two seconds (2000ms) function printadd (a, b) { console.log(a + "+" + b + "=" + (a+b)); } parameters fn : function a function to be delayed. ms : number number of milliseconds to delay the
execution of fn. arguments : mixed additional arguments to pass to fn upon
execution once(fn) creates a version of the input function that can only be called one time. repeated calls to the modified function will have no effect, returning the value from the original call. useful for initialization functions, instead of having to set a boolean flag and checking it later. let { once } = require("sdk/lan...
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
enote function, around line 345 (figure 3). fixme: figure 3: inserting a breakpoint start debugger type in some text into the quicknote screen, and then select save current tab from the menu. this should halt the program at the spot where you inserted the breakpoint with venkman, and start the debugger. the local variables screen should always display variables and objects during step-by-step
execution. with functions that include a lot of variables, this will be hard to read, so you can point out specific variables that you want to watch (figure 4). watched variables appear under the watches tab, and are updated every time they are evaluated. you can then continue with stepwise
execution and watch the changes in the program and variables. once you’ve finished your inspection, you can cont...
... the author has done almost no work developing extensions, but has used this to investigate how extensions were implemented. ...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
ry reviewer will generally reject the submission! parsing json mozilla provides native json support since firefox 3. there is simply no need to parse json using eval. additionally, parsing json retrieved from a remote location becomes a security vulnerability when parsed with the eval function. basically, you are executing remote code with full chrome access; that is, introducing a remote code
execution vulnerability. even if you trust the remote server; for example, because it is one you rent and administer yourself, there is a huge security risk, because of, but not limited to: you might discontinue your project or sell it, so that it is possible another person with malicious intentions takes over your domain. the server and/or domain name might be compromised. if using an unencrypted, in...
...out("alert('attack!'); format_computer(); alert('done');", 100); as a general rule of thumb, just don't pass code around as strings and execute it by calling eval, settimeout and friends. alternative: use (anonymous) functions you can always create a small anonymous function to pass around instead. closures will ensure the code is still valid, even if your outer function already returned from
execution. addeventlistener("load", function() { myaddon.init(); myaddon.onload(); }, true); function doxhr() { //... var response = xhr.responsetext; settimeout(function() { alert(response); }, 100); } alternative: use function.bind() introduced in javascript 1.8.5 function.bind is a new utility function that you may use to (partially) bind parameters to functions. addeventlistener("load...
Local Storage - Archive of obsolete content
y and storing private information locally without deleting it. a good argument can be done for both, so it is up to you to choose what to do in this case. the fuel library has an uninstall event you can use to perform these operations. logging good logging is essential in all kinds of software projects. any extension that is more complex than a hello world needs some way to log errors and trace
execution without having to fire up a debugger. it used to be the case that custom logging solutions were necessary, but mozilla labs have come up with a javascript implementation of a logger similar to the log4j logger used in java projects. the logger is called log4moz and it is implemented as a javascript code module, so it only works on firefox 3 and above. to use this logger, you need to copy the lo...
...ig("this is a config message."); this._logger.debug("this is a debug message."); this._logger.trace("this is a trace message."); you can filter the output of the global logger or any specific logger instance by setting the level property. during development you should use the "all" level, but for release versions it's usually better to move the level up to "warn", so that the log is compact and
execution is more efficient. note: we recommend that all exception catch blocks include some logging at the error or warn levels, and in general you should use logging freely in order to have as much information as possible to fix bugs and know what is going on. don't log inside functions that are called too often, such as mouseover event handlers, or certain http activity listeners. this impacts performa...
Setting Up a Development Environment - Archive of obsolete content
o overlay a window, and how to replace default css style rules. you can see the names of the files involved, which gives you a good starting point when looking into the mozilla source. you can even change styles, attributes and execute javascript code in it, although that's not completely reliable. javascript debugger the name says it all. the venkman javascript debugger is a great way to trace
execution of your javascript code. to debug extension and browser code, right-click on the loaded scripts panel and uncheck exclude browser files. the list of loaded scripts will grow long to include all of the scripts in firefox. having our file naming conventions prove very useful in this case. you can set breakpoints, step in and out of methods, and even get profiling information from javascript execut...
... this extension has seen little maintenance in quite some time, so it is very buggy. ...
Metro browser chrome tests - Archive of obsolete content
bout:blank is loaded"); } }); function test() { runtests(); } gtests contains individual tests that make up the library of tests your test file will contain. each test can have start up and tear down logic, plus the body of the test contained in run(). the test file can contain other functions which will be ignored unless invoked by test(). gtests make use of promises and tasks for managing
execution. test comparison functions used in metro browser chrome tests are identical to those supported by mochitests, see how the comparison functions work in the mochitest documentation for more details. helper functions the eventutils helper functions are available on the eventutils object defined in the global scope. additional metro specific test helpers can be found in /browser/metro/base/tests/moch...
... content (html files, images, etc.) should be stored in sub directories to avoid polluting the main test directory. sub directories for larger test suites may also be created. exceptions in tests any exceptions thrown under test() will be caught and reported as a general failure. setup(), teardown(), and run() each have individual exception handlers to prevent one method from interfering with the
execution of another. an exception in any of these methods will cause a test failure. additional built-in framework test checks will run after the completion of each individual test insuring tests clean up properly. for more information on test
execution see the main test exectuon loop in head.js. adding a new browser chrome test to the tree to add a new metro browser chrome test add the test file to the b...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
year minus 1900, originally meant to return "98" for 1998. getyear was deprecated in ecmascript version 3 and replaced with getfullyear(). internet explorer uses an obsolete behavior for getyear(), similar to netscape 4 and earlier, returning the year minus 1900 for years 1900-1999, and the full year for any other year. (i.e. for 1999, getyear() returns 99, for 2000, it returns 2000). javascript
execution differences different browsers execute javascript differently. for example, the following code assumes that the div node already exists in the dom by the time the script block executes: ... <div id="foo">loading...</div> <script> document.getelementbyid("foo").innerhtml = "done."; </script> however, this is not guaranteed. to be sure that all elements exist, you should use the onload event...
...s are also hardware-related -- slower systems can reveal bugs that faster systems hide. one concrete example is window.open, which opens a new window: <script> function doopenwindow(){ var mywindow = window.open("about:blank"); mywindow.location.href = "http://www.ibm.com"; } </script> the problem with the code is that window.open is asynchronous -- it does not block the javascript
execution until the window has finished loading. therefore, you may execute the line after the window.open line before the new window has finished. you can deal with this by having an onload handler in the new window and then call back into the opener window (using window.opener). differences in javascript-generating html javascript can, through document.write, generate html on the fly from a string. the...
Using XPInstall to Install Plugins - Archive of obsolete content
cute method of the install object to execute the binary. you can also call the execute method of the file object if you wish to actually install the file you are executing, rather than have it deleted. you can pass command line parameters to the executable. an example of calling the execute method from the install object on an executable that has a temporary life span (and is not needed after one
execution) is: // initialize the installation .... // initinstall(..... ) has already been called // using the install object's execute method to block on a native installer execute("setup.exe", "-s", true); // in the above sample, assume that running "setup -s" from the // command prompt runs the setup executable, and that "-s" is some // invocation parameter defined by the setup.exe file, perhaps ...
... installer execute("setup.exe", "-s", true); // in the above sample, assume that running "setup -s" from the // command prompt runs the setup executable, and that "-s" is some // invocation parameter defined by the setup.exe file, perhaps to force // the installer to run silently. we are passing "-s" to the setup file. // by passing 'true' we are telling the install script to block // on the
execution of the installable, and do it synchronously // must call performinstall to make it all happen... err = getlasterror(); if (!err) performinstall(); else cancelinstall(err); installing plugin files to the current browser installing to the current browser is the task that is the most important for the xpi package to succeed in. here is a code snippet that accomplishes this: // name of the...
Learn XPI Installer Scripting by Example - Archive of obsolete content
if you choose not to register the installed software or do the verifications at the front end of the installation, then at a minimum, the install scripts mustinitialize, add the files to be installed, and execute. note also that when you call methods on the install--as you do so often in installation scripts (getfolder, initinstall, addfile, and...
...ly execute the installation. note that until this point, the install calls you have been making on the install object are preliminary only. recall that an install process takes the following general form: initinstall(); if (verify_space()) { err = add_dirs_and_files; register_files; if (err==success) { performinstall() }; else { cancelinstall() }; } in this arrangement, the actual
execution of the installation is checked against the errors returned from the addition of files to the installation, which may itself have been conditioned on some verification of version and necessary disk space. the actual install code used to execute the installation appears in theinstall.js file as follows: if (err==success) { err = performinstall(); logcomment("performinstall() return...
NPN_PluginThreadAsyncCall - Archive of obsolete content
void (*func)(void *), void *userdata); parameters the function has the following parameters: plugin pointer to the current plug-in instance. func pointer to the function to call on the correct thread. userdata pointer to the data to pass to the function func once called. returns nothing. description causes asynchronous
execution of the specified function pointer on the "plug-in thread", passing in the specified user data pointer when it is called. the "plug-in thread" is the thread hosting the plug-in, which may be either the browser's main thread or the plug-in process if the plug-in is being executed out-of-process. it is the application's responsibility to perform any synchronization between the thread calling npn_plu...
...d the user data is not deallocated until the browser executes the call. there are inherent race conditions between calling this function and termination of the plug-in instance. the browser might not execute calls successfully registered with this api call during plug-in termination. plug-ins should perform appropriate synchronization with the code in their npp_destroy() routine to ensure correct
execution and avoid memory leaks. calling npn_pluginthreadasynccall() on the "browser main thread" or the "plug-in thread" is legal; the call to npn_pluginthreadasynccall() returns immediately. after control returns to the browser, it is free to call the function with its argument from this thread. see also npp out-of-process plugins ...
Settings - Archive of obsolete content
the debugger has its own settings menu, which you can access from an icon in the toolbar: each setting is a simple on/off switch: auto prettify minified sources with this option enabled, the debugger will automatically detect minified js files and pretty-print them. pause on exceptions when this option is enabled,
execution of the script will automatically pause whenever a javascript exception is thrown. ...
...ied sources with this option enabled, the debugger will automatically detect minified js files and pretty-print them. pause on exceptions when this option is enabled,
execution of the script will automatically pause whenever a javascript exception is thrown. ignore caught exceptions if this option is set (it is set by default) and "pause on exceptions" is set, then
execution will pause on an exception only if that exception is not caught. this is usually the behavior you want. you don't generally want to pause
execution when an exception that is thrown is caught, since that generally indicates that your program is handling it properly. show panes on startup when this option is enabled, the debugger's variables pane is visible when you first start...
Scratchpad - Archive of obsolete content
code you want to run. if you don't select anything, all the code in the window will be run. then choose the way you want the code to run using the buttons along the top, using the execute menu, or using the context menu. the code is executed in the scope of the currently selected tab. any variables you declare outside of a function will be added to the global object for that tab. there are four
execution options available. run when you choose the run option, the selected code is executed. this is what you'd use to execute a function or other code that manipulates the content of your page without needing to see the result. inspect the inspect option executes the code just like the run option; however, after the code returns, an object inspector is opened to let you examine the returned value.
...f or developing add-ons. to do this check "enable chrome and add-on debugging" in the developer tool settings. once you've done this, the environment menu has a browser option; once that's selected, your scope is the entire browser rather than just the page content, as you will see from examining some globals: window /* [object chromewindow] */ gbrowser /* [object xulelement] */ the scratchpad
execution context is set to browser when a snippet file has // -sp-context: browser on the first line. keyboard shortcuts command windows macos linux open the scratchpad shift + f4 shift + f4 shift + f4 run scratchpad code ctrl + r cmd + r ctrl + r run scratchpad code, display the result in the object inspector ctrl + i cmd + i ctr...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
of all the operating contexts of jaxer, you'll need to specify how your scripts should behave using the runat attribute of the script tag (or by setting a runat property on a javascript function object). the common values for this attribute are explained below, though there are more than just these. runat=”client” – code contained in this block is restricted to
execution client-side, which is also what happens if no runat attribute is specified. runat=”server” – code contained in this block is restricted to
execution server-side. runat=”both” – code may be invoked on the client or server side. runat=”server-proxy” – allows for the exposure of server-side javascript functions to the browser. jaxer manages ajax calls behind the s...
...e!"; } </script> <script runat="client"> alert( exposed() ); alert( notexposed() ); </script> there are two blocks of scripts defined, one with runat set to server and the other set to client. this creates a strict separation of the two environments. as it stands, the code in the client block would throw an error since the server-side javascript is not within scope. if you intend to allow the
execution of server-side javascript from the client-side, you can correct the code in listing 1 by doing one of three things. change the runat attribute value of server to server-proxy. add a statement inside the server-side script block to expose a particular server-side function to the browser. this statement is of the form <functionname>.proxy = true. ensure the server-side function na...
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
and what functions are called from within that function, etc. when a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function. any functions that are called by that function are added to the call stack further up, and run where their calls are reached. when the current function is finished, the interpreter takes it off the stack and resumes
execution where it left off in the last code listing. if the stack takes up more space than it had assigned to it, it results in a "stack overflow" error. example function greeting() { // [1] some codes here sayhi(); // [2] some codes here } function sayhi() { return "hi!"; } // invoke the `greeting` function greeting(); // [3] some codes here the code above would be executed like this:...
...tion invocation. add the greeting() function to the call stack list. call stack list: - greeting execute all lines of code inside the greeting() function. get to the sayhi() function invocation. add the sayhi() function to the call stack list. call stack list: - sayhi - greeting execute all lines of code inside the sayhi() function, until reaches its end. return
execution to the line that invoked sayhi() and continue executing the rest of the greeting() function. delete the sayhi() function from our call stack list. call stack list: - greeting when everything inside the greeting() function has been executed, return to its invoking line to continue executing the rest of the js code. delete the greeting() function from the call stack list. call ...
What are browser developer tools? - Learn web development
e current element. find out more find more out about the inspector in different browsers: firefox page inspector ie dom explorer chrome dom inspector (opera's inspector works the same as this) safari dom inspector and style explorer the javascript debugger the javascript debugger allows you to watch the value of variables and set breakpoints, places in your code that you want to pause
execution and identify the problems that prevent your code from executing properly. to get to the debugger: firefox: select ➤ web developer ➤ debugger or press ctrl + shift + s to open the javascript debugger. if the tools are already displayed, click on the debugger tab. chrome: open the developer tools and then select the sources tab. (opera works the same way.) edge and internet explorer 11: ...
...r tab. exploring the debugger there are three panes in the javascript debugger on firefox. file list the first pane on the left contains the list of files associated with the page you are debugging. select the file you want to work with from this list. click on a file to select it and view its contents in the center pane of the debugger. source code set breakpoints where you want to pause
execution. in the following image, the highlight on the number 18 shows that the line has a breakpoint set. watch expressions and breakpoints the right-hand pane shows a list of the watch expressions you have added and breakpoints you have set. in the image, the first section, watch expressions, shows that the listitems variable has been added. you can expand the list to view the values in the array. ...
Introducing asynchronous JavaScript - Learn web development
ndividually handled in each level of the "pyramid". promises avoid inversion of control, unlike old-style callbacks, which lose full control of how the function will be executed when passing a callback to a third-party library. the nature of asynchronous code let's explore an example that further illustrates the nature of async code, showing what can happen when we are not fully aware of code
execution order and the problems of trying to treat asynchronous code like synchronous code. the following example is fairly similar to what we've seen before (see it live, and the source). one difference is that we've included a number of console.log() statements to illustrate an order that you might think the code would execute in. console.log ('starting'); let image; fetch('coffee.jpg').then((response...
...ole.log('there has been a problem with your fetch operation: ' + error.message); }); console.log ('all done!'); the browser will begin executing the code, see the first console.log() statement (starting) and execute it, and then create the image variable. it will then move to the next line and begin executing the fetch() block but, because fetch() executes asynchronously without blocking, code
execution continues after the promise-related code, thereby reaching the final console.log() statement (all done!) and outputting it to the console. only once the fetch() block has completely finished running and delivering its result through the .then() blocks will we finally see the second console.log() message (it worked :)) appear. so the messages have appeared in a different order to what you might e...
What is JavaScript? - Learn web development
your page? here we'll actually start looking at some code, and while doing so, explore what actually happens when you run some javascript in your page. let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our how css works article). when you load a web page in your browser, you are running your code (the html, css, and javascript) inside an
execution environment (the browser tab). this is like a factory that takes in raw materials (the code) and outputs a product (the web page). a very common use of javascript is to dynamically modify html and css to update a user interface, via the document object model api (as mentioned above). note that the code in your web documents is generally loaded and executed in the order it appears on the page. ...
...uments is generally loaded and executed in the order it appears on the page. if the javascript loads and tries to run before the html and css it is affecting has been loaded, errors can occur. you will learn ways around this later in the article, in the script loading strategies section. browser security each browser tab has its own separate bucket for running code in (these buckets are called "
execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website. this is a good security measure — if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things. note: ther...
Website security - Learn web development
data rendered by the browser, or user files that are uploaded and displayed. the best defense against xss vulnerabilities is to remove or disable any markup that can potentially contain instructions to run the code. for html this includes elements, such as <script>, <object>, <embed>, and <link>. the process of modifying user data so that it can't be used to run scripts or otherwise affect the
execution of server code is known as input sanitization. many web frameworks automatically sanitize user input from html forms by default. sql injection sql injection vulnerabilities enable malicious users to execute arbitrary sql code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. a successful injection attack might spoof identities, create new...
...tack, a malicious user attempts to access parts of the web server file system that they should not be able to access. this vulnerability occurs when the user is able to pass filenames that include file system navigation characters (for example, ../../). the solution is to sanitize input before using it. file inclusion. in this attack, a user is able to specify an "unintended" file for display or
execution in data passed to the server. when loaded, this file might be executed on the web server or the client-side (leading to an xss attack). the solution is to sanitize input before using it. command injection. command injection attacks allow a malicious user to execute arbitrary system commands on the host operating system. the solution is to sanitize user input before it might be used in system cal...
Handling common JavaScript problems - Learn web development
ows: on the left, you can select the script you want to debug (in this case we have only one). the center panel shows the code in the selected script. the right-hand panel shows useful details pertaining to the current environment — breakpoints, callstack and currently active scopes. the main feature of such tools is the ability to add breakpoints to code — these are points where the
execution of the code stops, and at that point you can examine the environment in its current state and see what is going on. let's get to work. the error is now being thrown at line 51. click on line number 51 in the center panel to add a breakpoint to it (you'll see a blue arrow appear over the top of it). now refresh the page (cmd/ctrl + r) — the browser will pause
execution of the code at line 51. a...
... have showheroes() the function we are currently in, and second we have onload, which stores the event handler function containing the call to showheroes(). under scopes, you'll see the currently active scope for the function we are looking at. we only have three — showheroes, block, and window (the global scope). each scope can be expanded to show the values of variables inside the scope when
execution of the code was stopped. we can find out some very useful information in here. expand the showheroes scope — you can see from this that the heroes variable is undefined, indicating that accessing the members property of jsonobj (first line of the function) didn't work. you can also see that the jsonobj variable is storing a text string, not a json object. exploring further down the call ...
Error codes returned by Mozilla APIs
to set a path that isn't valid for the platform. for example, if a character in the path is not valid for a filename. in addition, this error may occur when a relative path is supplied to a method that expects an absolute path and vice versa. ns_error_file_unresolvable_symlink (0x80520002) an attempt was made to access a symbolic link to a file or directory which does not exist. ns_error_file_
execution_failed (0x80520003) an attempt to launch or execute a file failed because the file is not executable. nsifile.isexecutable() may be used to check if a file is executable. ns_error_file_unknown_type (0x80520004) an call was made to nsifile.create() with an invalid type. only normal_file_type and directory_type are allowed. ns_error_file_destination_not_dir (0x80520005) an attempt was made to ...
..._xpath_bad_bang (0x80600018) ns_error_xpath_illegal_char (0x80600019) ns_error_xpath_binary_expected (0x8060001a) ns_error_xpath_invalid_expression_evaluated (0x8060001c) ns_error_xpath_unbalanced_curly_brace (0x8060001d) xslt errors errors that can occur when using xslt. ...
Performance
abmm.addmessagelistener("my-addon:paragraph-count", callback); tabmm.loadframescript("data:,sendasyncmessage('my-addon:paragraph-count', {num: content.document.queryselectorall('p').length})", false) } function decoratebutton(button, count) { // do stuff with result } this executes the script only when it is needed and only in one tab and allows it to be garbage-collected immediately after
execution. as long as it the action does not happen frequently the memory and startup savings should outstrip the added cost of script evaluation. delaying the script registration until the session is restored my provide some middle ground for some addons. it does not provide the same memory footprint reductions but it improves application startup. beam down information in advance to avoid synchronous...
...ed on their local copy. see the previous chapter on how to efficiently replicate addon state to each process. clean up on addon unload bad: all the previous examples, *even the "better" ones* if your addon is restartless or uses the sdk then updates or the user turning it off and on will load to unload/reload events. not handling those properly can lead to duplicate or conflicting code
execution, especially when messages are sent. it can also lead to conflicts between the old and new code. under some circumstances it may even cause exceptions when attempting to register something twice under the same id. better: // addon.js function onunload() { services.mm.removedelayedframescript("resources://my-addon/framescript.js"); services.ppmm.removedelayedprocessscript("resources://my-addo...
NSPR's Position On Abrupt Thread Termination
ble programs. threads are not processes. abrupt termination has been available in the unix/c environment for some time (exit()), and i assume that the basic semantics defined there are applicable here. in that environment, exit() may be called and any time, and results in the calling thread's immediate termination. in the situation where it was defined (unix), which has only a single thread of
execution, that is equivalent to terminating the process. the process abstraction is then responsible for closing all open files and reclaiming all storage that may have been allocated during the process' lifetime. this practice does not extend to threads. threads run within the confines of a process (or similar abstractions in other environments). threads are lightweight because they do not maintain the f...
...the stack unwinds. in these cases, the presence of the data is recorded only on the stack, known only to the single thread (normally referred to as encapsulated). the problem with abrupt termination is that it can happen at any time, to a thread that is coded correctly to handle both normal and exceptional situations, but will be unable to do so since it will be denied the opportunity to complete
execution. it can happen because it called out of its own scope into some lazily implemented library. nspr's answer to this is that there is no abrupt thread termination. all threads must unwind and return from their root function. if they cannot, because of some state corruption, then they must assume that the corruption, like the state, is shared, and their only resource is for the process to terminate. ...
Hacking Tips
ication will add an instruction which abuse the stack pointer to store an immediate value (the lir id) to a location which would never be generated by any sane compiler. thus when dumping the assembly under gdb, this kind of instructions would be easily noticeable. viewing the mirgraph of ion/odin compilations (from gdb) with gdb instrumentation, we can call iongraph program within gdb when the
execution is stopped. this instrumentation adds an iongraph command when provided with an instance of a mirgenerator*, will call iongraph, graphviz and your prefered png viewer to display the mir graph at the precise time of the
execution. to find mirgenetator* instances, is best is to look up into the stack for optimizemir, or codegenerator::generatebody. optimizemir function has a mir argument, and th...
...(gdb) cond 7 *$word & $mask // (gdb) cont // // note that this is *not* a watchpoint on a single bit. it is a watchpoint on // the whole word, which will trigger whenever the word changes and the // selected bit is set after the change. // // so if the bit changing is the desired one, this is exactly what you want. // but if a different bit changes (either set or cleared), you may still stop //
execution if the $mask bit happened to already be set. gdb does not expose // enough information to restrict the watchpoint to just a single bit. most of the time, you will want js::gc::black (or you can just use 0) for the 2nd param to js::debug::getmarkmask. ...
JIT Optimization Strategies
t optimization strategy information which the jit coach tool can parse to display in its ui. 2. provide a user-browsable documentation of optimization strategies, how they work, how they are defeated, and options for how to re-enable them. spidermonkey's optimizing jit, ionmonkey, uses various strategies to optimize operations. the most commonplace operations that are relevant for fast program
execution are property accesses and function calls. optimization information is currently collected for the following operations: getproperty (obj.prop) setproperty (obj.prop = val) getelement (obj[elemname]) setelement (obj[elemname] = val) call (func(...)) at each operation site, ionmonkey tries a battery of strategies, from the most optimized but most restrictive to the least optimized but lea...
... slower than the other optimization strategies, and are an indication that the type inference engine has failed to collect enough information to guide the optimization process. call call_inline a function call f(x) usually pushes a frame onto the call stack. inlining a call site conceptually copies the body of the callee function and pastes it in place of the call site and avoids pushing a new
execution frame. usually, hot functions do well to be inlined. this is one of the most important optimizations the jit performs. ion inlines both interpreted (i.e., written in javascript) functions and native (i.e., built-ins such as math.sin implemented in c++). a successfully inlined call site has the outcome inlined. failure to inline comes in two flavors: unable (e.g., unable to determine exact call...
JS::Compile
this article covers features introduced in spidermonkey 17 compile a script for
execution. syntax // added in spidermonkey 45 bool js::compile(jscontext *cx, const js::readonlycompileoptions &options, js::sourcebufferholder &srcbuf, js::mutablehandlescript script); bool js::compile(jscontext *cx, const js::readonlycompileoptions &options, const char *bytes, size_t length, js::mutablehandlescript script); bool js::compile(jscontext *cx, const js::readonlycompileoptions &options, const char16_t *chars, size_t length, js::mutablehandlescript script); bool js::compile(jscontext *cx, const js::readonlycompileoptions &options, file *file, js::mutablehandlescript script); bool js::compile(jscon...
...aracters. file file * file handle containing the function. filename const char * name of file or url containing the function. used to report filename or url in error messages. script js::mutablehandlescript out parameter. on success, script receives the result script. description js::compile compiles a script, srcbuf, chars, bytes, or file, for
execution. the script is associated with a js object. srcbuf, chars, bytes is the string containing the text of the script. length indicates the size of the text version of the script in characters. file is the filehandle containing the text of the script. filename is the name of the file (or url) containing the script. this information is included in error messages if an error occurs during compilation...
JS::CompileOffThread
this article covers features introduced in spidermonkey 31 compile a script off thread for
execution. syntax bool js::cancompileoffthread(jscontext *cx, const js::readonlycompileoptions &options, size_t length); bool js::compileoffthread(jscontext *cx, const js::readonlycompileoptions &options, const char16_t *chars, size_t length, js::offthreadcompilecallback callback, void *callbackdata); jsscript * js::finishoffthreadscript(jscontext *maybecx, jsruntime *rt, void *token); typedef void (*js::offthreadcompilecallback)(void *token, void *callbackdata); name type description cx / maybe jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_...
... chars const char16_t * string containing the script to compile. length size_t the length of chars or bytes, in characters. callback js::offthreadcompilecallback a callback function invoked when the compilation. callbackdata / token void * pointer to application-defined data. description js::compileoffthread compiles a script, chars for
execution. the script is associated with a js object. chars is the string containing the text of the script. length indicates the size of the text version of the script in characters. after successfully triggering an off thread compile of a script, the callback will eventually be invoked with the specified data and a token for the compilation. the callback will be invoked while off the main thread, so it...
JS_CallFunction
assing to the function. obsolete since jsapi 30 argv jsval * pointer to the array of argument values to pass to the function. obsolete since jsapi 30 rval js::mutablehandlevalue out parameter. on success, *rval receives the return value from the function call. description js_callfunction calls a specified function, fun, on an object, obj. in terms of function
execution, the object is treated as this. js_callfunctionname calls a function with specified name, name on an object obj. if js engine fails to get the function, it returns false. js_callfunctionvalue calls a specified function, fval on an object obj. js_callfunctionvalue(cx, obj, fval, args, rval) is analogous to the javascript statement rval = fval.apply(obj, args);. in args, pass a reference to the ...
...ent you pass to the function; the number of arguments you pass may be different from the number of arguments defined for the function. obsolete since jsapi 30. in argc, indicate the number of arguments passed to the function. in argv, pass a pointer to the actual argument values to use. rval is a pointer to a variable that will hold the function's return value, if any, on successful function
execution. if the called function executes successfully, js_callfunction returns true. otherwise it returns false, and rval is undefined. calling js_callfunction is safe only if the fun argument could be passed to js_getfunctionobject safely: that is, it is a function implemented by a jsnative or jsfastnative or the result of a call to js_compilefunction, js_compileucfunction, js_compilefunctionforprinci...
JS_CompileScript
compiles a script for
execution. syntax // added in spidermonkey 45 bool js_compilescript(jscontext *cx, const char *ascii, size_t length, const js::compileoptions &options, js::mutablehandlescript script); bool js_compileucscript(jscontext *cx, const char16_t *chars, size_t length, const js::compileoptions &options, js::mutablehandlescript script); // obsolete since jsapi 39 bool js_compilescript(jscontext *cx, js::handleobject obj, const char *ascii, size_t length, const js::compileoptions &options, js::mutablehandlescript script); bool js_compileucscript(jscontext *cx, js::handleobject obj, const char16_t *char...
...ii or chars const char * or const char16_t * string containing the script to compile. length size_t the length, in characters, of source. options js::compileoptions & compile options. script js::mutablehandlescript out parameter. on success, script receives the result script. description js_compilescript compiles a script, source, for
execution. js_compileucscript is the unicode version of the function. the script is associated with a js object. ascii and chars are the string containing the text of the script. length indicates the size of the text version of the script in characters. on success, js_compilescript and js_compileucscript stores the newly compiled script to *script and returns true. otherwise, they report an error, stores...
JS_CompileScriptForPrincipals
obsolete since jsapi 28this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. compile a security-enabled script for
execution. syntax jsscript * js_compilescriptforprincipals(jscontext *cx, jsobject *obj, jsprincipals *principals, const char *src, size_t length, const char *filename, unsigned int lineno); jsscript * js_compileucscriptforprincipals(jscontext *cx, jsobject *obj, jsprincipals *principals, const jschar *src, size_t length, const char *filename, unsigned int lineno); jsobject * js_compilescriptforprincipalsversion(jscontext *cx, jsobject *obj, jsprincipals *principals, const char *src, size_t length, const char *filename, unsigned int lineno, jsversion v...
...e const char * name of file or url containing the function. used to report filename or url in error messages. lineno unsigned int line number. used to report the offending line in the file or url if an error occurs. version jsversion javascript version for the script. description js_compilescriptforprincipals compiles a security-enabled script, src, for
execution. js_compileucscriptforprincipals is the unicode version of the function. the script is associated with a js object. principals is a pointer to the jsprincipals structure that contains the security information to associate with this script. src is the string containing the text of the script. length indicates the length of the script, in characters. filename is the name of the file (or url) con...
JS_SetBranchCallback
replaced with js_setoperationcallback. ...
...he callback returns js_false without raising an exception, then the javascript engine immediately stops running the script with an uncatchable error. the engine does not execute finally blocks in this case; this is the same behavior as any native method or callback. description js_setbranchcallback specifies a callback function that is automatically called when a script branches backward during
execution, when a function returns, and at the end of the script. one typical use for a callback is in a client application to enable a user to abort a script that runs for a long time. another use is to call js_maybegc periodically. the callback is called very frequently, so applications should ensure that the callback runs very quickly most of the time. typically an application only wants to do somethin...
JS_SetFunctionCallback
using this function may have a significant performance impact. ...
... cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fcb jsfunctioncallback the callback to execute when javascript functions are invoked and exited. specify null to stop calling the current callback. the callback must not modify the current state of
execution. the call stack cannot be relied upon, because this callback may be invoked from the jit code when the stack frame and context are in an indeterminate state. description js_setfunctioncallback sets a c function to be called each time a javascript function is invoked or exits. fcb is a pointer to the c function to call. note that debuggers should probably use js_setcallhook in preference...
jsdIStackFrame
underlying context wrapped by this jsdicontext. top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false| otherwise. this attribute is only valid for contexts which implement nsiscriptcontext. setting or getting this attribute on any other context will throw a ns_error_no_interface exception. stack frame objects. these are only valid inside the jsdi
executionhook which gave it to you. after you return from that handler the bottom frame, and any frame you found attached through it, are invalidated via the jsdiephemeral interface. once a jsdistackframe has been invalidated all method and property accesses will throw a ns_error_not_available exception. method overview boolean eval(in astring bytes, in autf8string filename, in unsigned long line, out j...
...ed all method and property accesses will throw a ns_error_not_available exception. method overview boolean eval(in astring bytes, in autf8string filename, in unsigned long line, out jsdivalue result); attributes attribute type description callee jsdivalue function object running in this stack frame. read only. callingframe jsdistackframe link to the caller's stack frame. read only.
executioncontext jsdicontext executon context. read only. functionname autf8string function name executing in this stack frame. read only. isconstructing boolean true if stack frame is constructing a new object. read only. isdebugger boolean true if stack frame represents a frame created as a result of a debugger evaluation. read only. isnative boolean true if stack frame represents a native frame.
Index
ro <rhp@netscape.com> contents 37 mail event system mozilla mail requires an event system to notify different subsystems that data has changed. this document describes the system that events are passed amongst the mail objects. 38 mailnews filters mailnews, thunderbird mailnews filters consist of a set of search terms, and a set of filter actions. filter
execution is done by evaluating the search terms using the core mailnews/base/search code, and then applying the filter hits when the search terms match. for new incoming messages, the protocol specific object that handles new messages calls nsimsgfilterlist::applyfilterstohdr and passes itself in as nsimsgfilterhitnotify interface to handle filter hits. e.g., imap, pop3. 39 mailnews protocols ...
...rd the article "creating a custom column" will get you well on the road to creating your own columns and populating them with custom data. the customdbheaders preference article provides information on a preference setting that exposes custom header data for use in a custom column within thunderbird's main view. 102 detect opening folder thunderbird some actions require
execution every time you open a folder (for example, registering a custom column handler. to do this you need to capture the select event of the folder [[xul:tree|tree]] whose id is (conveniently) foldertree like so: 103 filter incoming mail filter, incoming, mails, thunderbird to filter incoming mail, the first step is to detect new messages inconming. the, you've got components.inter...
MailNews Filters
mailnews filters consist of a set of search terms, and a set of filter actions. filter
execution is done by evaluating the search terms using the core mailnews/base/search code, and then applying the filter hits when the search terms match. for new incoming messages, the protocol specific object that handles new messages calls nsimsgfilterlist::applyfilterstohdr and passes itself in as nsimsgfilterhitnotify interface to handle filter hits. e.g., imap, pop3. applyfilterstohdr will in turn call the applyfilterhit method of the passed in nsimsgfilterhitnotify interface ptr. the protocol specific code will then apply all of the actions of the filter to the current msg header. ...
...imsgfilterlist::applyfilterstohdr and passes itself in as nsimsgfilterhitnotify interface to handle filter hits. e.g., imap, pop3. applyfilterstohdr will in turn call the applyfilterhit method of the passed in nsimsgfilterhitnotify interface ptr. the protocol specific code will then apply all of the actions of the filter to the current msg header. if one of the actions is a move, or a stop filter
execution action, we move on to the next header; otherwise, we move on to the next filter. in the case of pop3, filter
execution is synchronous. for each new header, we evaluate the filter criteria and apply the actions synchronously, including moving a message to an other local folder, and advance to the next header. for imap, we tend to initiate the urls synchronously, but because we don't run two urls s...
Set event listener breakpoints - Firefox Developer Tools
n up the javascript debugger, and find and expand the event listener breakpoints section in the right hand column. to break when event listeners are hit, check the boxes next the events you are interested in. all of the standard events supported in your version of firefox are listed, arranged by which api or api area they're part of. now when a keydown, keyup, keypress, or input event occurs,
execution will pause as soon as it enters the listener code. when
execution pauses, the source pane displays the highlighted line of the javascript code that is next to be executed, along with the surrounding code for context. in addition, you get a box overlaid on the viewport saying "paused on event breakpoint", with buttons to step over that line of code or resume
execution. you could add regular br...
...f however you have multiple elements, all of which have event listeners attached that you want to break on, this becomes an enormous time saver. this is also useful when debugging code that you're unfamiliar with, to save time over hunting down your event handler within your code, or when trying to understand why a web site isn't working as expected in your browser. use event breakpoints to stop
execution at the triggering event for the action that fails, then step through the code or watch the console to see what happens. logging on events in firefox 71 onwards, the “log” checkbox is available in the event listener breakpoints list. selecting this and then choosing some events to break on will mean that when you step through code, information about events fired will be logged to the console...
Debugger-API - Firefox Developer Tools
both firefox’s built-in developer tools and the firebug add-on use debugger to implement their javascript debuggers. however, debugger is quite general, and can be used to implement other kinds of tools like tracers, coverage analysis, patch-and-continue, and so on. debugger has three essential qualities: it is a source level interface: it operates in terms of the javascript language, not machine language. ...
...environment, associating variable names with storage locations. environments may belong to a running stack frame, captured by a function closure, or reflect some global object’s properties as variables. the debugger instance itself is not really a shadow of anything in the debuggee; rather, it maintains the set of global objects which are to be considered debuggees. a debugger observes only
execution taking place in the scope of these global objects. you can set functions to be called when new stack frames are pushed; when new code is loaded; and so on. omitted from this picture are debugger.source instances, which represent javascript compilation units. a debugger.source can furnish a full copy of its source code, and explain how the code entered the system, whether via a call to eval, a <s...
The Firefox JavaScript Debugger - Firefox Developer Tools
emotely, for example on an android device running firefox for android. see remote debugging to learn how to connect the debugger to a remote target. to find your way around the debugger, here's a quick tour of the ui. how to to find out what you can do with the debugger, refer to the following how-to guides. open the debugger pretty-print a minified file search use a source map pause
execution you probably want to pause the
execution of your code, in order to see what is going on at various points. there are multiple ways to tell the debugger how and when to pause: set a breakpoint set a conditional breakpoint set an xhr breakpoint set event listener breakpoints break on exceptions use watchpoints for property reads and writes break on dom mutation disable breakpoints co...
...probably want to pause the
execution of your code, in order to see what is going on at various points. there are multiple ways to tell the debugger how and when to pause: set a breakpoint set a conditional breakpoint set an xhr breakpoint set event listener breakpoints break on exceptions use watchpoints for property reads and writes break on dom mutation disable breakpoints control
execution what can you do after
execution pauses? step through code black box a source debug worker threads debug eval sources look at values you probably want to see the value of variables or expressions, either during
execution or when it is paused. set a logpoint set watch expressions reference keyboard shortcuts source map errors ...
Intensive JavaScript - Firefox Developer Tools
: the top half of this is the waterfall overview. it gives us a compressed view of the waterfall, which tells us what kinds of operations the browser is doing during the recording. the pink says that we are mostly performing css calculations and possibly reflow: this is the css animation that's running throughout the profile. then there are three solid blocks of orange, representing javascript
execution, one for each time we pressed the button. the bottom half, which is correlated with the timeline summary in time, shows frame rate. we can see that frame rate is pretty healthy for most of the recording, but collapses completely whenever we press the button. we can select one of these periods and have a closer look at it in the main waterfall view: here, when we pressed the button, the brows...
...ct one of these periods and have a closer look at it in the main waterfall view: here, when we pressed the button, the browser ran a javascript function, or series of functions, that blocked the main thread for 71.73ms, or more than four times our frame budget. which function, though? by switching to the flame chart view we can find out: this shows us the js call stack at this point in the
execution. at the top of the stack is a function called calculateprimes(), and we can see its filename and line number. here's the code, together with its immediate caller: const iterations = 50; const multiplier = 1000000000; function calculateprimes(iterations, multiplier) { var primes = []; for (var i = 0; i < iterations; i++) { var candidate = i * (multiplier * math.random()); var isprime...
The JavaScript input interpreter - Firefox Developer Tools
hem in single-line mode. note that the result might be an error message. expressions that have side effects are not evaluated. you can enable or disable instant evaluation via the settings ("gear") menu in the web console toolbar. the menuitem instant evaluation has a checkmark next to it when the feature is enabled, which is missing when it is disabled. select the menuitem to change the state.
execution context code that you have executed becomes part of the
execution context, regardless of what editing mode you were in when you executed it. for example, if you type a function definition in the multi-line editor, and click run, you can switch to single-line mode and still use your function. syntax highlighting the text you enter has syntax highlighting as soon as you have typed enough for t...
...run, you can switch to single-line mode and still use your function. syntax highlighting the text you enter has syntax highlighting as soon as you have typed enough for the highlighter to parse it and infer the meanings of the "words". the output is highlighted as well where appropriate. note: syntax highlighting is not visible in your browser if accessibility features have been enabled.
execution history the interpreter remembers expressions you've typed. to move back and forward through your history: in single-line mode, use the up and down arrows. in multi-line mode, use the ⋀ and ⋁ icons in the editing panel's toolbar. the expression history is persisted across sessions. to clear the history, use the clearhistory() helper function. you can initiate a reverse search throug...
AudioWorkletGlobalScope - Web APIs
properties currentframe read only returns an integer that represents the ever-increasing current sample-frame of the audio block being processed. ...
... properties currentframe read only returns an integer that represents the ever-increasing current sample-frame of the audio block being processed. ...
FeaturePolicy - Web APIs
featurepolicy.allowedfeatures returns a list of names of all features supported by the user agent and allowed by the feature policy. ...
... featurepolicy.allowedfeatures returns a list of names of all features supported by the user agent and allowed by the feature policy. note that features appearing on this list might still be behind a user permission. ...
WebGL best practices - Web APIs
them to a program object. eagerly lose contexts too webgl_lose_context.losecontext() can be used to release a webgl context and its resources eagerly. use this if you are finished with any contexts, such as probe contexts, or if you hit a fallback case. flush when expecting results (like queries or rendering frame completion) flush tells the implementation to push all pending commands out for
execution, flushing them out of the queue, instead of waiting for more commands to enqueue before sending for
execution. for example, it is possible for the following to never complete without context loss: sync = glfencesync(gl_sync_gpu_commands_complete, 0); glclientwaitsync(sync, 0, gl_timeout_ignored); webgl doesn't have a swapbuffers call by default, so a flush can help fill the gap, as well. use...
...e following to never complete without context loss: sync = glfencesync(gl_sync_gpu_commands_complete, 0); glclientwaitsync(sync, 0, gl_timeout_ignored); webgl doesn't have a swapbuffers call by default, so a flush can help fill the gap, as well. use webgl.flush() when not using requestanimationframe when not using raf, (such as when using rpaf; see below) use webgl.flush() to encourage eager
execution of enqueued commands. because raf is directly followed by the frame boundary, an explicit webgl.flush() isn't really needed with raf. avoid blocking api calls in production (e.g. geterror, getparameter) certain webgl entry points cause synchronous stalls on the calling thread. even basic requests can take as long as 1ms, but they can take even longer if they need to wait for all graphics work ...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
ty is to use function's bind. example: settimeout(function(arg1){}.bind(undefined, 10), 1000); the "this" problem when you pass a method to settimeout() (or any other function, for that matter), it will be invoked with a this value that may differ from your expectation. this issue is explained in detail in the javascript reference. explanation code executed by settimeout() is called from an
execution context separate from the function from which settimeout was called. the usual rules for setting the this keyword for the called function apply, and if you have not set this in the call or with bind, it will default to the window (or global) object. it will not be the same as the this value for the function that called settimeout. see the following example: myarray = ['zero', 'one', 'two']; mya...
...as been called'); } settimeout(foo, 0); console.log('after settimeout'); will write to the console: after settimeout foo has been called this is because even though settimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity; not immediately. currently-executing code must complete before functions on the queue are executed, thus the resulting
execution order may not be as expected. deferral of timeouts during pageload starting in firefox 66, firefox will defer firing settimeout and setinterval timers while the current tab is loading. firing is deferred until the mainthread is deemed idle (similar to window.requestidlecallback()), or until the load event is fired. maximum delay value browsers including internet explorer, chrome, safari, an...
WindowOrWorkerGlobalScope - Web APIs
thods these methods are defined on the windoworworkerglobalscope mixin, and implemented by window and workerglobalscope. windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding. windoworworkerglobalscope.btoa() creates a base-64 encoded ascii string from a string of binary data. windoworworkerglobalscope.clearinterval() cancels the repeated
execution set using windoworworkerglobalscope.setinterval(). windoworworkerglobalscope.cleartimeout() cancels the delayed
execution set using windoworworkerglobalscope.settimeout(). windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap. optionally the source is cropped to the rectangle of pixels originating at ...
...of different image sources, and returns a promise which resolves to an imagebitmap. optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh. windoworworkerglobalscope.fetch() starts the process of fetching a resource from the network. windoworworkerglobalscope.queuemicrotask() enqueues a microtask—a short function to be executed after
execution of the javascript code completes and control isn't being returned to a javascript caller, but before handling callbacks and other tasks. this lets your code run without interfering with other, possibly higher priority, code, but before the browser runtime regains control, potentially depending upon the work you need to complete. windoworworkerglobalscope.setinterval() schedules a function to ex...
Synchronous and asynchronous requests - Web APIs
asynchronous request if you use an asynchronous xmlhttprequest, you receive a callback when the data has been received. this lets the browser continue to work as normal while your request is being handled. ...
... line 3 sends the request. the null parameter indicates that no body content is needed for the get request. line 5 checks the status code after the transaction is completed. if the result is 200 -- http's "ok" result -- the document's text content is output to the console. example: synchronous http request from a worker one of the few cases in which a synchronous request does not usually block
execution is the use of xmlhttprequest within a worker. example.html (the main page): <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>mdn example</title> <script type="text/javascript"> var worker = new worker("mytask.js"); worker.onmessage = function(event) { alert("worker said: " + event.data); }; worker.postmessage("hello"); </scr...
animation-fill-mode - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. it is often convenient to use the shorthand property animation to set all animation properties at once. ...
...ple animations */ animation-fill-mode: none, backwards; animation-fill-mode: both, forwards, none; values none the animation will not apply any styles to the target when it's not executing. the element will instead be displayed using any other css rules applied to it. this is the default value. forwards the target will retain the computed values set by the last keyframe encountered during
execution. the last keyframe depends on the value of animation-direction and animation-iteration-count: animation-direction animation-iteration-count last keyframe encountered normal even or odd 100% or to reverse even or odd 0% or from alternate even 0% or from alternate odd 100% or to al...
Getting Started - Developer guides
t domain name on all of your pages or you will get a "permission denied" error when you call open(). a common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld. if you really need to send a request to another domain, see http access control (cors). the optional third parameter sets whether the request is asynchronous. if true (the default), javascript
execution will continue and the user can interact with the page while the server response has yet to arrive. this is the first a in ajax. the parameter to the send() method can be any data you want to send to the server if post-ing the request. form data should be sent in a format that the server can parse, like a query string: "name=value&anothername="+encodeuricomponent(myvar)+"&so=on" or other forma...
... note: if you're sending a request to a piece of code that will return xml, rather than a static html file, you must set response headers to work in internet explorer. if you do not set header content-type: application/xml, ie will throw a javascript "objec...
Clear-Site-Data - HTTP
ms such as: localstorage (executes localstorage.clear), sessionstorage (executes sessionstorage.clear), indexeddb (for each database execute idbfactory.deletedatabase), service worker registrations (for each service worker registration, execute serviceworkerregistration.unregister), appcache, websql databases, filesystem api data, plugin data (flash via npp_clearsitedata). "
executioncontexts" indicates that the server wishes to reload all browsing contexts for the origin of the response (location.reload). "*" (wildcard) indicates that the server wishes to clear all types of data for the origin of the response. if more data types are added in future versions of this header, they will also be covered by it. examples sign out of web site if a user signs out of your websit...
...lso be covered by it. examples sign out of web site if a user signs out of your website or service, you might want to remove locally stored data. you can achieve that by adding the clear-site-data header when sending the page confirming that logging out from the site has been accomplished successfully (https://example.com/logout, for example): clear-site-data: "cache", "cookies", "storage", "
executioncontexts" clearing cookies if this header is delivered with the response at https://example.com/clear-cookies, all cookies on the same domain https://example.com and any subdomains (like https://stage.example.com, etc), will be cleared out. clear-site-data: "cookies" specifications specification status title clear site data working draft initial definition. ...
CSP: script-src - HTTP
csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. ...
...supports sha256, sha384 and sha512. content-security-policy: script-src 'sha256-b2yphkaxnvfwtrchibabymubfzdvfkkxhbwtwiddvf8=' when generating the hash, don't include the <script> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. <script>var inline = 1;</script> unsafe eval expressions the 'unsafe-eval' source expression controls several script
execution methods that create code from strings. if 'unsafe-eval' isn't specified with the script-src directive, the following methods are blocked and won't have any effect: eval() function() when passing a string literal like to methods like: window.settimeout("alert(\"hello world!\");", 500); window.settimeout window.setinterval window.setimmediate window.execscript (ie < 11 only...
Index - HTTP
nstructs the client to require the use of subresource integrity for scripts or styles on the page. 46 csp: sandbox csp, directive, http, security the http content-security-policy (csp) sandbox directive enables a sandbox for the requested resource similar to the <iframe> sandbox attribute. it applies restrictions to a page's actions including preventing popups, preventing the
execution of plugins and scripts, and enforcing a same-origin policy. 47 csp: script-src csp, directive, http, reference, security the http content-security-policy (csp) script-src directive specifies valid sources for javascript. this includes not only urls loaded directly into <script> elements, but also things like inline script event handlers (onclick) and xslt stylesheets which ca...
...cripts, and enforcing a same-origin policy. 47 csp: script-src csp, directive, http, reference, security the http content-security-policy (csp) script-src directive specifies valid sources for javascript. this includes not only urls loaded directly into <script> elements, but also things like inline script event handlers (onclick) and xslt stylesheets which can trigger script
execution. 48 csp: style-src csp, directive, http, reference, security the http content-security-policy (csp) style-src directive specifies valid sources for stylesheets. 49 csp: upgrade-insecure-requests csp, directive, http, reference, security the http content-security-policy (csp) upgrade-insecure-requests directive instructs user agents to treat all of a site'...
HTTP Index - HTTP
use of subresource integrity for scripts or styles on the page. 97 csp: sandbox csp, content-security-policy, directive, http, sandbox, security the http content-security-policy (csp) sandbox directive enables a sandbox for the requested resource similar to the <iframe> sandbox attribute. it applies restrictions to a page's actions including preventing popups, preventing the
execution of plugins and scripts, and enforcing a same-origin policy. 98 csp: script-src csp, content, content-security-policy, directive, http, reference, script, security, script-src, source the http content-security-policy (csp) script-src directive specifies valid sources for javascript. this includes not only urls loaded directly into <script> elements, but also things like inline...
... script-src csp, content, content-security-policy, directive, http, reference, script, security, script-src, source the http content-security-policy (csp) script-src directive specifies valid sources for javascript. this includes not only urls loaded directly into <script> elements, but also things like inline script event handlers (onclick) and xslt stylesheets which can trigger script
execution. 99 csp: script-src-attr csp, content, content-security-policy, directive, http, reference, script, security, script-src, source the http content-security-policy (csp) script-src-attr directive specifies valid sources for javascript inline event handlers. this includes only inline script event handlers like onclick, but not urls loaded directly into <script> elements. ...
Control flow and error handling - JavaScript
for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements. if no matching label is found, the program looks for the optional default clause: if a default clause is found, the program transfers control to that clause, executing the associated statements. if no default clause is found, the program resumes
execution at the statement following the end of switch. (by convention, the default clause is written as the last clause, but it does not need to be so.) break statements the optional break statement associated with each case clause ensures that the program breaks out of switch once the matched statement is executed, and then continues
execution at the statement following switch. if break is omi...
...the end of switch. (by convention, the default clause is written as the last clause, but it does not need to be so.) break statements the optional break statement associated with each case clause ensures that the program breaks out of switch once the matched statement is executed, and then continues
execution at the statement following switch. if break is omitted, the program continues
execution inside the switch statement (and will evaluate the next case, and so on). example in the following example, if fruittype evaluates to 'bananas', the program matches the value with case 'bananas' and executes the associated statement. when break is encountered, the program exits the switch and continues
execution from the statement following switch. if break were omitted, the statement for case ...
Functions - JavaScript
ccess to). however, the outer function does not have access to the variables and functions defined inside the inner function. this provides a sort of encapsulation for the variables of the inner function. also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function
execution, if the inner function manages to survive beyond the life of the outer function. a closure is created when the inner function is somehow made available to any scope outside the outer function. var pet = function(name) { // the outer function defines a variable called "name" var getname = function() { return name; // the inner function has access to the "name" variable of the ...
...nd be consistent. self.age = 0; setinterval(function growup() { // the callback refers to the `self` variable of which // the value is the expected object. self.age++; }, 1000); } alternatively, a bound function could be created so that the proper this value would be passed to the growup() function. an arrow function does not have its own this; the this value of the enclosing
execution context is used. thus, in the following code, the this within the function that is passed to setinterval has the same value as this in the enclosing function: function person() { this.age = 0; setinterval(() => { this.age++; // |this| properly refers to the person object }, 1000); } var p = new person(); predefined functions javascript has several top-level, built-in functions: ...
Introduction - JavaScript
thods. javascript is a very free-form language compared to java. you do not have to declare all variables, classes, and methods. you do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. variables, parameters, and function return types are not explicitly typed. java is a class-based programming language designed for fast
execution and type safety. type safety means, for instance, that you can't cast a java integer into an object reference or access private memory by corrupting java bytecodes. java's class-based model means that programs consist exclusively of classes and their methods. java's class inheritance and strong typing generally require tightly coupled object hierarchies. these requirements make java programming m...
...(function(){"use strict"; before your code, and add })(); to the end of your code. you will learn what these mean, but for now they can be thought of as doing the following: massively improve performance. prevent stupid semantics in javascript that trip up beginners. prevent code snippets executed in the console from interacting with one-another (e.g., having something created in one console
execution being used for a different console
execution). « previousnext » ...
Regular expressions - JavaScript
t substring. replaceall() executes a search for all matches in a string, and replaces the matched substrings with a replacement substring. split() uses a regular expression or a fixed string to break a string into an array of substrings. when you want to know whether a pattern is found in a string, use the test() or search() methods; for more information (but slower
execution) use the exec() or match() methods. if you use exec() or match() and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, regexp. if the match fails, the exec() method returns null (which coerces to false). in the following example, the script uses the exec() method to find a m...
...ferent behaviors for further info about the different behaviors.) if you want to construct the regular expression from a string, yet another alternative is this script: var myre = new regexp('d(b+)d', 'g'); var myarray = myre.exec('cdbbdbsbz'); with these scripts, the match succeeds and returns the array and updates the properties shown in the following table. results of regular expression
execution. object property or index description in this example myarray the matched string and all remembered substrings. ['dbbd', 'bb', index: 1, input: 'cdbbdbsbz'] index the 0-based index of the match in the input string. 1 input the original string. 'cdbbdbsbz' [0] the last matched characters. 'dbbd' myre l...
switch - JavaScript
, executing the associated statements. (if multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.) if no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. ...
...clause, executing the associated statements. if no default clause is found, the program continues
execution at the statement following the end of switch. by convention, the default clause is the last clause, but it does not need to be so. the optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues
execution at the statement following switch. if break is omitted, the program continues
execution at the next statement in the switch statement. examples using switch in the following example, if expr evaluates to bananas, the program matches the value with case case 'bananas' and executes the associated statement. when break is encountered, the program breaks out of switch and executes the statement fo...
Communicating With Other Scripts - Archive of obsolete content
t.js document.defaultview.addeventlistener('message', function(event) { console.log(event.data); // message from page script console.log(event.origin); }, false); using custom dom events as an alternative to using postmessage() you can use custom dom events to communicate between page scripts and content scripts. messaging from content script to page script from firefox 30 onwards, the
execution environment for content scripts has changed, so content scripts can't directly share objects with page scripts. this affects the use of custom events to send messages from content scripts to page scripts. before firefox 30 here's an example showing how to use custom dom events to send a message from a content script to a page script, before firefox 30. first, "main.js" will create a page-mod...
Interacting with page scripts - Archive of obsolete content
g/"); // listen.js document.defaultview.addeventlistener('message', function(event) { console.log(event.data); // message from page script console.log(event.origin); }, false); using custom dom events as an alternative to using postmessage() you can use custom dom events to communicate between page scripts and content scripts. content script to page script from firefox 30 onwards, the
execution environment for content scripts has changed, so content scripts can't directly share objects with page scripts. this affects the use of custom events to send messages from content scripts to page scripts. before firefox 30 here's an example showing how to use custom dom events to send a message from a content script to a page script, before firefox 30. first, "main.js" will create a page-mod...
page-mod - Archive of obsolete content
r to the gotelement message. the content script receives the getelements message, retrieves all elements of that type, and for each element sends a gotelement message containing the element's innerhtml. the "main.js" code receives each gotelement message and logs the contents. if multiple documents that match the page-mod's include pattern are loaded, then each document is loaded into its own
execution context with its own copy of the content scripts. in this case the listener assigned to onattach is called once for each loaded document, and the add-on code will have a separate worker for each document. to learn much more about communicating with content scripts, see the guide to content scripts and in particular the chapter on communicating using port. mapping workers to tabs the worker has...
test/httpd - Archive of obsolete content
this module was removed in firefox 36, please use the addon-httpd npm module instead. an http server for the mozilla platform, which can be used in unit tests. usage the most basic usage is: var { startserverasync } = require("sdk/test/httpd"); var srv = startserverasync(port, basepath); require("sdk/system/unload").when(function cleanup() { srv.stop(function() { // you should continue
execution from this point. }) }); this starts a server in background (assuming you're running this code in an application that has an event loop, such as firefox). the server listens at http://localhost:port/ and serves files from the specified directory. you can serve static content or use sjs scripts, as described in documentation on developer.mozilla.org. you can also use nshttpserver to start the ser...
Low-Level APIs - Archive of obsolete content
ironment. system/unload register callbacks that are called when a module is unloaded. system/xul-app information about the application on which your add-on is running. tabs/utils functions for working with xul tabs and the xul tabbrowser object. test/assert implements the assert interface defined in the commonjs unit testing specification version 1.1. test/harness test harness setup and
execution. test/httpd an http server for the mozilla platform, which can be used in unit tests. test/runner sets up unit tests. test/utils helper methods used in the commonjs unit testing suite. ui/button/action add a button to the firefox user interface. ui/button/toggle add a toggle button to the firefox user interface. ui/frame create html iframes, using bundled html, css and javascript, tha...
On page load - Archive of obsolete content
progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. progress listeners implement the nsiwebprogresslistener interface. ...
JavaScript timers - Archive of obsolete content
the setinterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. the setimmediate() function can be used instead of the settimeout(fn, 0) method to execute heavy operations in ie. ...
Code snippets - Archive of obsolete content
miscellaneous miscellaneous useful code fragments html to dom using a hidden browser element to parse html to a window's dom javascript libraries here are some javascript libraries that may come in handy. stringview a library that implements a stringview view for javascript typed arrays. this lets you access data in typed arrays using c-like string fu...
Displaying web content in an extension without security issues - Archive of obsolete content
a typical example is an rss reader extension that would take the content of the rss feed (html code), format it nicely and insert into the extension window. the issue that is commonly overlooked here is that the rss feed could contain some malicious javascript code and it would then execute with the privileges of the extension — meaning that it would get full access to the browser (cookies, history etc) and to user’s files. these issues can easily be avoided by making use of the existing security mechanisms in the mozilla codebase. ...
Chapter 1: Introduction to Extensions - Archive of obsolete content
e history menu. locationbar separates a url’s domain and path in the location bar for easier reading. feature enhancing extensions fixme: update this. these extensions enhance features that already exist in firefox. tab mix plus offers detailed tab-related settings. prefbar gives access to numerous preferences from the toolbar. noscript enables and disables javascript
execution on a site-by-site basis. web application integration extensions fixme: update this. the use the apis of certain web applications to provide certain pieces of information. new feature extensions fixme: update this. extensions can add completely new features to firefox. this class of extension requires a greater level of knowledge and programming ability. greasemonkey userchrome.js bo...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
; note: this is unneeded when the code is part of an extension, and will result in rejection if submitted to addons.mozilla.org. permit by dialog try adding the contents of listing 2 to test.xul, before the line var ioservice = …, and re-open it in firefox. you should now see the confirmation dialog shown in figure 1. pressing the "permit" button grants universalxpconnect permission in this
execution context, making it possible to run xpconnect temporarily. an xpconnect-wrapped nsiioservice message should appear. if you check “apply these privileges in the future”, all local files will be able to run xpconnect without confirmation in the future. this is extremely dangerous, and you should never check this option. editing prefs.js opening test.xul will produce the dialog shown in figure...
Adding Events and Commands - Archive of obsolete content
the most commonly used event is the onload event, which is used in overlays and other windows to detect when the window has loaded and then run initialization code: // rest of overlay code goes here. window.addeventlistener( "load", function() { xulschoolchrome.browseroverlay.init(); }, false); you can do something similar with the onunload event, to do any cleanup you may need. please read appendix a for recommendations on how to use the load event to initialize your add-on without having a negative performance impact on firefox. ...
Connecting to Remote Content - Archive of obsolete content
requires you to set the content type of the request and to pass the post data to the send() method as below. request.open("post", url, true); request.setrequestheader("content-type", "application/x-www-form-urlencoded"); request.send("data=hello&version=2"); the third parameter for the open method specifies whether the request should be handled asynchronously or not. in asynchronous mode code
execution continues immediately after the send call. in synchronous mode the code and user interface are blocked while waiting for a response to come back. note: requests can take a long time to process and you don't want users to be stuck waiting while a request is obtained and processed. therefore, it is very important that xmlhttprequest calls are always done asynchronously. now let's look at the most...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
many add-ons need to dynamically generate dom content, either xul or html, from their scripts. for security reasons, and to prevent errors, care needs to be taken to avoid evaluating arbitrary text as html. failure to do so can lead to
execution or remote scripts, and in the worst cases to privilege escalation which can leave a user's pc open to remote attack. building dom trees in most cases, dom trees should be built exclusively with dom creation methods. the following methods will all safely create a dom tree without risk of remote
execution. json templating jsontodom.namespaces = { html: "http://www.w3.org/1999/xhtml", xul: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" }; jsontodom.defaultnamespace = jsontodom.namespaces.html; function jsontodom(jsontemplate, doc,...
JavaScript Object Management - Archive of obsolete content
ter, after a delay in miliseconds specified by the second parameter. in this case we set the delay to 0, which means the function should be executed as soon as possible. firefox has a minimum delay of 10-15ms (taken from this blog post), so it won't really run instantly. it is more than enough to let the window finish its load. use window.settimeout and window.setinterval to control timed code
execution. in case you're using javascript code modules or xpcom objects, where a window object is not readily available, use an nsitimer instead. this post suggests a way to achieve a true zero ms timeout, as a simple way to achieve parallelism in js code. notice the way we send callback functions as parameters, and the use of an alternate reference for this which we always name that. this is all nec...
Index of archived content - Archive of obsolete content
using third-party modules (jpm) bootstrapped extensions code snippets alerts and notifications autocomplete bookmarks boxes canvas code snippets cookies customizing the download progress bar delayed
execution dialogs and prompts downloading files drag & drop embedding svg examples and demos from articles file i/o finding window handles forms related code snippets html in xul for rich tooltips html to dom isdefaultnamespace js xpcom javascript debug...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
example of tb5: # jar -tvf /usr/lib/thunderbird/omni.jar | grep prefcalls.js 7499 sat nov 05 09:21:34 cet 2011 defaults/autoconfig/prefcalls.js traditionally (previous apps versions) is was in mozilla_home/default/autoconfig/prefcalls.js. the presence of pref("general.config.filename", "mozilla.cfg"); in any appropriate .js file (here we use autoconf.js dedicated file) enables the read and
execution of prefcalls.js. do not use the name all.js because it is reserved. ref: bug 690370 available functions are (see prefcalls.js file for details): function getprefbranch() function pref(prefname, value) function defaultpref(prefname, value) function lockpref(prefname, value) function unlockpref(prefname) function getpref(prefname) function getldapattributes(host, base, filter, attribs) function g...
Dehydra Function Reference - Archive of obsolete content
so a file is only included once and subsequent include calls are ignored. this is accomplished by recording every included file into the _includedarray in the current namespace. include example include("map.js") // includes map.js into toplevel var map = {} include("map.js", map) // includes map.js into the map object require({version:, strict:, werror:, gczeal:}) require is used to set runtime
execution flags. it also returns the current values of these flags. require supports optional named arguments via javascript object where each parameter is a property. if a property is not specified then it will not be passed to the runtime. version integer: this sets js version similar to version() in js 1.7. strict boolean: controls js strict mode werror boolean: turns js warnings into errors gczeal int...
Exception logging in JavaScript - Archive of obsolete content
as a result, if, for example, c++ code called a javascript component, which threw an exception, that exception would be logged to the console before control was returned to the c++ caller. this had the unintended consequence of logging "expected" errors at length into the console. javascript code is sometimes designed to throw exceptions to report a result condition back to the c++ caller. ...
Running Tamarin acceptance tests - Archive of obsolete content
221457 end date : 2010-09-28 10:39:26.751797 test time : 0:01:19.530340 passes : 59291 failures : 0 expected failures : 75 tests skipped : 76 the -f flag tells runtests.py to force recompilation of all the scripts. for help on runtests.py options, see below or use python runtests.py -h. notes on using acceptance runtests.py threading in order to speed up the
execution time of the acceptance testsuite, the runtests script automatically detects the number of cores on the machine and sets an equivalent number of threads. this can be overrided with the threads flag: python ./runtests.py --threads=3 threading on cygwin / windows due to an issue with cygwin python, threading does not work, and threads will always be set to 1. in order to use threading on windows y...
Event Handlers - Archive of obsolete content
d if that event matches all of the criteria specified by the handler. the most basic handler specifies the event to listen for and an action to take when the handler fires. this action can be specified either using an action attribute or by specifying the script as a child of the handler element. if both are specified, the attribute wins. in both cases the javascript body is compiled just before
execution; code that does not depend on the context of the event should be factored into normal javascript file. (note that there is a possibility that this may change in the future.) handlers are attached to the bound element, and they are registered by default for bubbling events. this means that <handler event="click" action="foo()"/> is analogous to onclick="foo()" defined on the bound element. th...
execute - Archive of obsolete content
ing args [, boolean blocking]); parameters the execute method has the following parameters: xpisourcepath the pathname of the file to extract and execute. (note that this path points into the xpi itself.) args a parameter string that is passed to the executable. (ignored on mac os). see note below. blocking a boolean value that specifies whether the installation should wait for the
execution of the file to finish before it resumes. default is false. see note below. the blocking parameter is not available as part of this method in versions of netscape before 6.1/mozilla 0.9.3. returns an integer error code. for a list of possible values, see return codes. description the execute method extracts the named file from the xpi file to a temporary file name. your code must call the pe...
performInstall - Archive of obsolete content
method of install syntax int performinstall(); parameters none. returns an integer error code. for a list of possible values, see return codes. in some situations the method may return other errors. in a few cases you may get a registry error. ...
Methods - Archive of obsolete content
installation of the software. confirm displays a confirm dialog box with the specified message and ok and cancel buttons. also allows custom button labels and a checkbox. deleteregisteredfile deletes the specified file and its entry in the client version registry. execute extracts a file from the xpi file to a temporary location and schedules it for later
execution. gestalt retrieves information about the operating environment. (mac os only) getcomponentfolder returns an object representing the directory in which a component is installed. getfolder returns an object representing a directory, for use with the addfile method. getlasterror returns the most recent non-zero error code. getwinprofile ...
Return Codes - Archive of obsolete content
the application as long as you did not replace operating system files. bad_package_name -200 a problem occurred with the package name supplied to initinstall unexpected_error -201 an unrecognized error occurred. access_denied -202 the user (or the os) did not grant the required security privilege.
execution_error -203 an error occurred executing the script no_install_script -204 installation script was not signed no_certificate -205 extracted file is not signed or the file (and, therefore, its certificate) could not be found. no_matching_certificate -206 extracted file was not signed by the certificate us...
Using Recursive Templates - Archive of obsolete content
tial reference node is the root of the xml source document, the results are two elements, one for each group element. however, a further step is done to retrieve an additional level of nodes. as each group has children itself, each result (in this case, each group) becomes the reference point for a futher iteration. the same query is executed again but using the groups generated from the previous
execution of the query. this time, the query generates a result for each person in the xml source. the content of the action body is again generated for each result, but instead of being inserted inside the outermost groupbox, this new content is inserted inside the content generated from the previous iteration. the content is always inserted directly inside the element with the uri attribute. the result i...
Using nsIXULAppInfo - Archive of obsolete content
see bug 809920, and in summary: // work around the fact that xpcshell doesn't have a proper app-info xpcom object. cu.import("resource://testing-common/appinfo.jsm"); updateappinfo(); older versions as stated above, older mozilla 1.7-based applications do not support nsixulappinfo. you'll have to write additional code if you choose to support those versions. for example, fi...
Multi-process plugin architecture - Archive of obsolete content
plugins are a frequent source of instability or crashes for browser users. when plugins run in the same process as the browser, any leaks or crashes in the plugin will affect the entire browser: in order to make the browser user experience better, it is possible to separate plugin
execution from the process in which the browser normally executes. when multi-process plugins are enabled, a shim layer in the browser implements the plugin api (the npp_ functions which would normally be implemented directly by the plugin). the calls are transferred to the plugin process via the ipdl protocol language. in the plugin process, the shim layer serves as a plugin host, implementing the npn_ functions used by the plugin, and forwards the calls to the plugin dll: multi-process plugins, also call...
Processing XML with E4X - Archive of obsolete content
ver the xml constructor when you need to create markup dynamically. with e4x it is easy to embed dynamic values in markup. variables and expressions can be used to create attribute values by simply wrapping them with braces ({}) and omitting quotation marks that would normally go around an attribute value, as the following example illustrates: var a = 2; var b = <foo bar={a}>"hi"</foo>; upon
execution the variable is evaluated and quotes are automatically added where appropriate. the preceding example would result in an xml object which looks like this: <foo bar="2">"hi"</foo>. in attribute substitution, quotation marks are escaped as " while apostrophes are handled normally. var b = 'he said "don\'t go there."'; var el = <foo a={b}/>; alert(el.toxmlstring()); // gives: <foo a="he said ...
LiveConnect Overview - Archive of obsolete content
object as one of its argument. to do so, you must define the corresponding formal parameter of the method to be of type jsobject. also, any time you use javascript objects in your java code, you should put the call to the javascript object inside a try...catch statement which handles exceptions of type netscape.javascript.jsexception. this allows your java code to handle errors in javascript code
execution which appear in java as exceptions of type jsexception. accessing javascript with jsobject for example, suppose you are working with the java class called javadog. as shown in the following code, the javadog constructor takes the javascript object jsdog, which is defined as type jsobject, as an argument: import netscape.javascript.*; public class javadog{ public string dogbreed; public s...
Archived open Web documentation - Archive of obsolete content
rogrammer define most of the behavior of an object in javascript. they are said to provide a meta-programming api. parallelarray the goal of parallelarray was to enable data-parallelism in web applications. the higher-order functions available on parallelarray attempted to execute in parallel, though they may fall back to sequential
execution if necessary. to ensure that your code executes in parallel, it is suggested that the functions should be limited to the parallelizable subset of js that firefox supports. properly using css and javascript in xhtml documents xhtml™ 1.0 the extensible hypertext markup language (second edition) d...
Anatomy of a video game - Game development
m, could be best for your game. the correct decision entirely depends on the trade-offs that you are willing (and unwilling) to make. the concern is mostly with switching to another option. fortunately, i do not have any experience with this, but i have heard it is an excruciating game of whack-a-mole. an important thing to remember for managed platforms, like the web, is that your loop may stop
execution for significant periods of time. this could occur when the user unselects your tab and the browser sleeps (or slows) its requestanimationframe callback interval. you have many ways to deal with this situation and this could depend on whether your game is single player or multiplayer. some choices are: consider the gap "a pause" and skip the time. you can probably see how this is problema...
Game promotion - Game development
new devs to befriend and learn from — and it will also get you involved in the community. if you make a good game for a competition and win some prizes in the process your game will automatically be promoted by the organizers and other attendees. you'll be rich and famous, or so they say. many great games get started as a quick, sloppy demo submitted to a competition. if both the idea and the
execution are good enough, you will succeed. plus competitions generally require games to follow a mandatory theme, so you can get creative around a theme if you are stuck for ideas. website and blog you should definitely create your own website containing all the information about your games, so people can see what you've worked on. the more information you can include the better — you should include ...
Buttons - Game development
note: the over event is the same as hover, out is when the pointer moves out of the button and down is when the button is pressed. now we need to define the startgame() function referenced in the code above: function startgame() { startbutton.destroy(); ball.body.velocity.set(150, -150); playing = true; } ...
2D maze game with device orientation - Game development
rsor = true; }, startgame: function() { this.game.state.start('howto'); } }; to create a new button there's add.button method with the following list of optional arguments: top absolute position on canvas in pixels. left absolute position on canvas in pixels. name of the image asset the button is using. function that will be executed when someone clicks the button. the
execution context. frame from the image asset used as the button's "hover" state. frame from the image asset used as the button's "normal" or "out" state. frame from the image asset used as the button's "click" or "down" state. the anchor.set is setting up the anchor point on the button for which all the calculations of the position are applied. in our case it's anchored half the way from the left edg...
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
o complete some kind of routine or action. here is a quick example: function greeting(name) { alert('hello ' + name); } function processuserinput(callback) { var name = prompt('please enter your name.'); callback(name); } processuserinput(greeting); the above example is a synchronous callback, as it is executed immediately. note, however, that callbacks are often used to continue code
execution after an asynchronous operation has completed — these are called asynchronous callbacks. a good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. this structure is used in many modern web apis, such as fetch(). learn more general knowledge callback on wikipedia ...
Conditional - MDN Web Docs Glossary: Definitions of Web-related terms
a condition is a set of rules that can interrupt normal code
execution or change it, depending on whether the condition is completed or not. an instruction or a set of instructions is executed if a specific condition is fulfilled. otherwise, another instruction is executed. it is also possible to repeat the
execution of an instruction, or set of instructions, while a condition is not yet fulfilled. learn more general knowledge condition on wikipedia control flow on mdn learn about it making decisions in your code — conditionals control flow and error handling in javascript on mdn ...
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
k at the code in the if and else sections, the lines promptuser and submitform could also be calls to other functions in the script. as you can see, control structures can dictate complex flows of processing even with only a few lines of code. control flow means that when you read a script, you must not only read from start to finish but also look at program structure and how it affects order of
execution. learn more general knowledge control flow on wikipedia technical reference javascript reference - control flow on mdn learn about it statements (control flow) on mdn ...
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
a global object is an object that always exists in the global scope. in javascript, there's always a global object defined. in a web browser, when scripts create global variables, they're created as members of the global object. (in node.js this is not the case.) the global object's interface depends on the
execution context in which the script is running. for example: in a web browser, any code which the script doesn't specifically start up as a background task has a window as its global object. this is the vast majority of javascript code on the web. code running in a worker has a workerglobalscope object as its global object. scripts running under node.js have an object called global as their global object. window object in the browser the window object is the global object in t...
Perceived performance - MDN Web Docs Glossary: Definitions of Web-related terms
ad and response times. speed index is a common metric for measuring perceived performance, though it's not perfect. other features, such as good ux design, including animations, and lazy loading, can make your site appear more responsive, even if the download and response times remain the same. actual performance is a measurement from when a request is made, through the downloading, parsing and
execution of all resources, and the final paint. while increased performance generally increases perceived performance, there are some techniques that can be used to increase perceived performance while marginally decreasing actual performance. there are front end optimization techniques that can improve perceived performance, such as adding the defer or async attribute to scripts, or placing scripts at t...
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
the context in which values and expressions are "visible" or can be referenced. if a variable or other expression is not "in the current scope," then it is unavailable for use. scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa. a function serves as a closure in javascript, and thus creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions. ...
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
each unit capable of executing code is called a thread. the main thread is the one used by the browser to handle user events, render and paint the display, and to run the majority of the code that comprises a typical web page or app. because these things are all happening in one thread, a slow website or app script slows down the entire browser; worse, if a site or app script enters an infinite loop, the entire browser will hang. this results in a frustrating, sluggish (or worse) user experience. however, modern javascript offers ways to create additional threads, each executing independently while possibly communicating between one another. ...
MDN Web Docs Glossary: Definitions of Web-related terms
x xforms xhr (xmlhttprequest) xhtml xinclude xlink xml xpath xquery xslt other 404 502 alpn at-rule attack byte-order mark character set client cryptosystem debug digital signature
execution flex-direction glsl interface library memory management routers self-executing anonymous function stylesheet vector image ...
Client-side form validation - Learn web development
$/; // many legacy browsers do not support the addeventlistener method. // here is a simple way to handle this; it's far from the only one. function addevent(element, event, callback) { let previouseventcallback = element["on"+event]; element["on"+event] = function (e) { const output = callback(e); // a callback that returns `false` stops the callback chain // and interrupts the
execution of the event callback. if (output === false) return false; if (typeof previouseventcallback === 'function') { output = previouseventcallback(e); if(output === false) return false; } } }; // now we can rebuild our validation constraint // because we do not rely on css pseudo-class, we have to // explicitly set the valid/invalid class on our email field addevent(window, ...
HTML forms in legacy browsers - Learn web development
th unobstructive javascript and graceful degradation techniques. please read the modernizr documentation. pay attention to performance even though scripts like modernizr are very aware of performance, loading a 200 kilobyte polyfill can affect the performance of your application. this is especially critical with legacy browsers; many of them have a very slow javascript engine that can make the
execution of all your polyfills painful for the user. performance is a subject on its own, but legacy browsers are very sensitive to it: basically, they are slow and the more polyfills they need, the more javascript they have to process. so they are doubly burdened compared to modern browsers. test your code with legacy browsers to see how they actually perform. sometimes, dropping some functionality leads...
Sending forms through JavaScript - Learn web development
; } // if not, read the file once the user selects it. file.dom.addeventlistener( "change", function () { if( reader.readystate === filereader.loading ) { reader.abort(); } reader.readasbinarystring( file.dom.files[0] ); } ); // senddata is our main function function senddata() { // if there is a selected file, wait it is read // if there is not, delay the
execution of the function if( !file.binary && file.dom.files.length > 0 ) { settimeout( senddata, 10 ); return; } // to construct our multipart form data request, // we need an xmlhttprequest instance const xhr = new xmlhttprequest(); // we need a separator to define each part of the request const boundary = "blob"; // store our body request in a string. l...
Making asynchronous programming easier with async and await - Learn web development
finally() async block, to show a final report on how the operation went — you can see this in action in our live example (see also the source code). the downsides of async/await async/await is really useful to know about, but there are a couple of downsides to consider. async/await makes your code look synchronous, and in a way it makes it behave more synchronously. the await keyword blocks
execution of all the code that follows until the promise fulfills, exactly as it would with a synchronous operation. it does allow other tasks to continue to run in the meantime, but your own code is blocked. this means that your code could be slowed down by a significant number of awaited promises happening straight after one another. each await will wait for the previous one to finish, whereas actually ...
Graceful asynchronous programming with Promises - Learn web development
n order to do something else with a successful result, or to gracefully handle a failure case. generally, you are less interested in the amount of time an async operation will take to return its result (unless of course, it takes far too long!), and more interested in being able to respond to it being returned, whenever that is. and of course, it's nice that it doesn't block the rest of the code
execution. one of the most common engagements you'll have with promises is with web apis that return a promise. let's consider a hypothetical video chat application. the application has a window with a list of the user's friends, and clicking on a button next to a user starts a video call to that user. that button's handler calls getusermedia() in order to get access to the user's camera and microphone. ...
A first splash into JavaScript - Learn web development
er objects let's play with some browser objects a bit. first of all, open up your program in a browser. next, open your browser developer tools, and make sure the javascript console tab is open. type guessfield into the console and the console shows you that the variable contains an <input> element. you'll also notice that the console autocompletes the names of objects that exist inside the
execution environment, including your variables! now type in the following: guessfield.value = 'hello'; the value property represents the current value entered into the text field. you'll see that by entering this command, we've changed the text in the text field! now try typing guesses into the console and pressing return. the console shows you that the variable contains a <p> element. now try ente...
Storing the information you need — Variables - Learn web development
your web browser's console. after that, try creating a variable (or two) with your own name choices. note: in javascript, all code instructions should end with a semi-colon (;) — your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. try to get into the habit of including it. you can test whether these values now exist in the
execution environment by typing just the variable's name, e.g. myname; myage; they currently have no value; they are empty containers. when you enter the variable names, you should get a value of undefined returned. if they don't exist, you'll get an error message — try typing in scoobydoo; note: don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all ...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
web page. the framework updates this virtual representation which is then synced with the "real" dom. this is much faster than directly updating the dom and allows the framework to apply many optimization techniques. these frameworks, by default, basically re-run all our javascript on every change against this virtual dom, and apply different methods to cache expensive calculations and optimize
execution. they make little to no attempt to understand what our javascript code is doing. svelte doesn't use a virtual dom representation. instead, it parses and analyzes our code, creates a dependency tree, and then generates the required javascript to update only the parts of the dom that need to be updated. this approach usually generates optimal javascript code with minimal overhead, but it also has ...
Setting up your own test automation environment - Learn web development
om lambdatest platform then you can do so by using lambdatest restful api. now if you go to your lambdatest automation dashboard, you'll see your test listed; from here you'll be able to see videos, screenshots, and other such data. you can retrieve network, command, exception, and selenium logs for every test within your test build. you will also find a video recording of your selenium script
execution. note: the help button on lambdatest automation dashboard will provide you with an ample amount of information to help you get started with lambdatest automation. you can also follow our documentation about running first selenium script in node js. note: if you don't want to write out the capabilities objects for your tests by hand, you can generate them using the selenium desired capabili...
What to do and what not to do in Bugzilla
ich are unconfirmed for more than a few days do not qualify for the blocker severity. the exceptions to this rule are platform-specific or compiler-specific bugs. basically, anything that prevents builds from building, running, or being used for dogfood (able to use bugzilla, tinderbox, lxr, etc.) is a blocker. bug reports about crashes, hangs, data-loss, or severe security exploits (e.g. remote
execution of arbitrary code) get the critical severity. priority/target milestone as stated in the bugzilla etiquette, you must not change the target milestone and priority fields. these fields are reserved for the developers. this also applies to bugs with target milestones in the past. reassigning bugs if a bug belongs to a different product or component it should be reassigned. when performing bug r...
Creating reftest-based unit tests
en by the creator of the reftest tool. there is one thing about automated tests that may not be obvious. there is really no way to construct a test that is too small. if you want to check something, and it seems trivial, that is ok. the cost of adding a new test to an automated suite is very, very low. for tests that are run manually, this is not true. the cost of thinking about and managing the
execution of a manual test is fairly high. this is why manual tests tend to get longer, include more steps and ultimately become a long list that actually tests a lot of things. so, create small tests. for example, it occurs to me that we assume that spaces between a element name and an attribute name have no effect, but do we know this is true? who checks this? it is completely trivial, but so what. i ca...
Makefiles - Best practices and suggestions
activity whenever a test touched a timestamp file in the directory to signal success. parallel make: add an explicit timestamp dependency (.done) that make can synchronize threaded calls on to avoid a race condition. # transient directory for storing timestamps ts=.ts ##################################################### ## extra dep needed to synchronize parallel
execution ##################################################### $(ts): $(ts)/.done $(ts)/.done: $(mkdir) -p $(dir $@) touch $@ # "clean" target garbage_dirs += $(ts) maintain clean targets - makefiles should be able to remove all content that is generated so "make clean" will return the sandbox/directory back to a clean state. targets = foo bar tans timestampdir = .ts all: $(timestampdir) $(tar...
mach
way of sub-commands. @commandargument this is a method decorator that tells mach about an argument to a mach command. the arguments to the decorator are passed to argparse.argumentparser.add_argument(). the class and method names can be whatever you want. they are irrelevant to mach. an instance of the @commandprovider class is instantiated by the mach driver if a command in it is called for
execution. the __init__ method of the class must take either 1 or 2 arguments (including self). if your class inherits from object, no explicit __init__ implementation is required (the default takes 1 argument). if your class's __init__ takes 2 arguments, the second argument will be an instance of mach.base.commandcontext. this object holds state from the mach driver, including the current directory, a han...
Developer guide
mozilla projects. dxr next generation of searching mozilla's source code. in active development. searchfox another option for mozilla code searching. indexes js as well as c++, includes blame capabilities. in active development. mozilla build vm a virtualbox compatible virtual machine configured with all the software needed to build and work on firefox. taskcluster taskcluster is the task
execution framework that supports mozilla's continuous integration and release processes. treeherder treeherder shows the status of the tree (whether or not it currently builds successfully). check this before checking in and out, to be sure you're working with a working tree. perfherder perfherder is used to aggregate the results of automated performance tests against the tree. crash tracking infor...
Experimental features in Firefox
g system, if the browser follows a system-wide color scheme setting). see bug 1550804 and bug 1137699 for more details. release channel version added enabled by default? nightly 72 no developer edition 72 no beta 72 no release 72 no preference name devtools.inspector.color-scheme-simulation.enabled
execution context selector this feature displays a button on the console's command line that lets you change the context in which the expression you enter will be executed. see bug 1605154 and bug 1605153 for more details. release channel version added enabled by default? nightly 75 no developer edition 75 no beta 75 no release 7...
Performance best practices for Firefox front-end engineers
weren’t any style changes requiring size or position recalculation above line 1, the clientheight information should be cached since the last reflow, and will not result in a new layout calculation. if you can avoid querying for the size or position of things in javascript, that’s the safest option—especially because it’s always possible that something earlier in this tick of javascript
execution caused a style change in the dom without you knowing it. note that given the same changes to the dom of a chrome ui document, a single synchronous uninterruptible reflow is no more computationally expensive than an interruptible reflow triggered by the 16ms tick. it is, however, advantageous to strive for reflow to only occur in the one place (the layout step of the 16ms tick) as opposed to mult...
OS.File for the main thread
ld rather create the directory with makedir and catch the error if the directory exists. this will ensure that you only need to perform one i/o operation rather than two. os.file.getcurrentdirectory() return the current directory promise<string> getcurrentdirectory() promise resolves to the path to the current directory. safety note: recall that the current directory can change during the
execution of the process. therefore, the information returned by this function may be false by the time you receive it. os.file.makedir() create a new directory promise<void> makedir( in string path, [optional] in object options ) throws os.file.error arguments path the full name of the directory to create. optionsoptional options for creating the directory. to specify options, pass an objec...
Examples
file.txt in your temporary directory."); } else { console.log("you don't have file.txt in your temporary directory."); } }); // unexpected errors should always be reported at the end of a promise chain. let lastpromise = newpromise.then(null, components.utils.reporterror); in this case, if the file existence check succeeds, the onfulfill callback is invoked. when the callback finishes
execution, newpromise will be fulfilled with an undefined fulfillment value, because the callback does not return any value. when newpromise is fulfilled, nothing happens, because no fulfillment callback is specified and the return value of the last then method is ignored. if the file existence check fails, for example because access is denied, promise is rejected with an os.file.error instance. this stat...
Promise
r). you can register a rejection callback on the returned promise instead (using catch() or then()), to process any exception occurred in either of the callbacks registered on this promise. note: when you call the then method multiple times on the same promise, the registered callbacks are always executed independently. for example, if an exception occurs in one callback, it does not affect the
execution of subsequent callbacks. the behavior of the callback only affects the promise returned by the then method with which the callback was registered, that is actually a different promise for each invocation of the method. promise then( function onfulfill, function onreject ); parameters onfulfill optional if the promise is fulfilled, this function is invoked with the fulfillment value of ...
PromiseWorker.jsm
ay should be passed here. if any of the arguments is a promise, it is resolved before posting the message. if any of the arguments needs to be transferred instead of copied, this may be specified by making the argument an instance of basepromiseworker.meta or by using the atransferlist argument. by convention, the last argument may be an object options with some of the following fields: out
executionduration {number|null} a parameter to be filled with the duration of the off main thread
execution for this call. aclosure optional an object holding strong references to value that should not be garbage-collected before the reply has been received. atransferlist optional an optional array of transferable objects to transfer ownership of. if the ownership of an object is transferred, it ...
XPCOMUtils.jsm
ty. example for this is seen at bottom of this page here. function definelazygetter( aobject, aname, alambda ); parameters aobject the object into which to add the new lazy getter function. aname the name of the getter function to create. alambda a function that returns the value the getter should return. this function is called exactly once. this will reference aobject during
execution of the function. definelazymodulegetter() defines a getter on a specified object for a module. the module will not be imported until first use. function definelazymodulegetter( aobject, aname, aresource, asymbol ); parameters aobject the object to define the lazy getter on. aname the name of the getter to define on aobject for the module. aresource the url used to obtain the...
JS::PerfMeasurement
a regular old instance variable, which you can read and even modify. all presently-measurable events are measured with counters, not timers; that is, there is no defined relation between the numbers you get from this interface, and wall-clock time. perfmeasurement* js::extractperfmeasurement(jsval wrapper) if you are the c++ side of an xpcom interface, and you want to benchmark only part of your
execution time but make the results available to javascript, you can declare a bare jsval argument in your .idl file and have javascript pass a perfmeasurement object that it created in that argument slot. the jsval you receive points to a javascript wrapper object. to extract the c++-level perfmeasurement object, call this function. it will return null if javascript passed in something with the wrong d...
Profiling with the Firefox Profiler
icon that appears to the right of the tree element as you hover over it. a "tree breadcrumb" will appear similar to the range breadcrumbs noted above. clicking the "javascript only" option will only show javascript code in the call tree. you could compare the time with this option checked and the total time to get an idea of how much time was spent running js. note that long-running js function
execution may not actually be taking as long as you think because further down the call stack there may be something like painting happening. clicking the "invert call stack" option will sort by the time spent in a function in descending order. note that the running time here is only the running time of that particular frame and not the total of all called instances of that function. you can see the sampl...
AsyncTestUtils extended framework
uses a nested event loop. in the future we will probably move the asynctestutils framework to a nested event loop in a backwards-compatible fashion. how does this affect my tests? thanks to javascript enhancements available on the mozilla platform, it is possible for a function to yield control in such a way that the function stops running at the line where you use a yield statement and resumes
execution on the next line when resumed. this allows you to write reasonably normal looking functions instead of having to chain together a whole bunch of functions and callbacks. your test functions need to agree to the following contract: the asynchronous function contract a function should yield false or return false when something asynchronous is going on. when the asynchronous operation is complet...
NSPR LOG MODULES
intended to always be logged 2 = pr_log_error: errors 3 = pr_log_warning: warnings 4 = pr_log_debug: debug messages, notices 5: everything! description specify a modulename that is associated with the name argument in a call to pr_newlogmodule and a non-zero level value to enable logging for the named modulename. special log module names are provided for controlling nspr's log service at
execution time. these controls should be set in the nspr_log_modules environment variable at
execution time to affect nspr's log service for your application. all the name all enables all log modules. to enable all log module calls to pr_log, set the variable as follows: set nspr_log_modules=all:5 timestamp including timestamp results in a timestamp of the form "2015-01-15 21:24:26.049906 utc - ...
PR_ASSERT
syntax #include <prlog.h> void pr_assert ( expression ); parameters the macro has this parameter: expression any valid c language expression that evaluates to true or false. returns nothing description this macro evaluates the specified expression. when the result is zero (false) the application terminates; otherwise the application continues. the macro converts the expression to a string and passes it to pr_assert, using file and line parameters from the compile-time environment. this macro compiles to nothing if compile-time options are not specified to enable logging. ...
PR_Assert
syntax #include <prlog.h> void pr_assert ( const char *s, const char *file, printn ln); parameters the function has these parameters: s a string to be displayed in the log. file the file name of the compilation unit containing this function call. ln the line number within the specified file of this function call. returns nothing description this function displays data in the log. ...
PR_CWait
onitor cache, pr_cwait waits for a notification that the monitor's state has changed. while the thread is waiting, it exits the monitor (just as if it had called pr_cexitmonitor as many times as it had called pr_centermonitor). when the wait has finished, the thread regains control of the monitor's lock with the same entry count as before the wait began. the thread waiting on the monitor resumes
execution when the monitor is notified (assuming the thread is the next in line to receive the notify) or when the interval specified in the timeout parameter has been exceeded. when the thread resumes
execution, it is the caller's responsibility to test the state of the monitored data to determine the appropriate action. ...
PR_GetThreadPrivate
recovers the per-thread private data for the current thread. syntax #include <prthread.h> void* pr_getthreadprivate(pruintn index); parameter pr_getthreadprivate has the following parameters: index the index into the per-thread private data table. returns null if the data has not been set. description pr_getthreadprivate may be called at any time during a thread's
execution. a thread can get access only to its own per-thread private data. do not delete the object that the private data refers to without first clearing the thread's value. ...
PR_QueueJob
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob( prthreadpool *tpool, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool. fn the function to be executed when the job is executed. arg a pointer to an argument passed to fn. joinable if pr_true, the job is joinable. if pr_false, the job is not joinable. see pr_joinjob. ...
PR_Wait
t be evaluated while in the monitor and within a loop. in pseudo-code, the sequence is as follows: pr_entermonitor(&ml); while (!expression) wait; ... act on the state change ... pr_exitmonitor(&ml); a thread can be resumed from a wait for a variety of reasons. the most obvious is that it was notified by another thread. if the value of timeout is not pr_interval_no_timeout, pr_wait resumes
execution after the specified interval has expired. if a timeout value is used, the boolean expression must include elapsed time as part of the monitored data. resuming from the wait is merely an opportunity to evaluate the expression, not an assertion that the expression is true. ...
NSPR API Reference
mbols from the main executable program process management and interprocess communication process management types and constants prprocess prprocessattr process management functions setting the attributes of a new process creating and managing processes multiwait receive system information and environment variables logging conditional compilation and
execution log types and variables prlogmoduleinfo prlogmodulelevel nspr_log_modules nspr_log_file logging functions and macros pr_newlogmodule pr_setlogfile pr_setlogbuffering pr_logprint pr_logflush pr_log_test pr_log pr_assert pr_assert pr_not_reached use example instrumentation counters named shared memory shared memory protocol named s...
NSS Memory allocation
at pool are put on an arena free list. when nss attempts to allocate more memory for an arena pool, the plarenapool code attempts to use an arena from its free list, and only gets a new arena from the heap if there are no arenas in the free list that are large enough to satisfy the request. there are two consequences of the use of plarenapools that affect leak analysis. they are: 1. at the end of
execution of a program, all the arenas in the free list will appear to have been leaked. this makes it difficult to tell arenas that are truly leaked from those that are merely in the free list. there is a function named pl_arenafinish that really frees all the arenas on the free list. see the prototype at http://mxr.mozilla.org/nspr/source/n.../ds/plarenas.h a program should call that function at the very...
NSS 3.19.2.1 release notes
192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decoder used by nss for handling streaming ber data. while the majority of nss uses a separate, unaffected der decoder, several public routines also accept ber data, and thus are affected. an attacker that successfully exploited these issues can overflow the heap and may be able to obtain remote code
execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. because nss includes portions of the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss. bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow exceptionally large allocations to be reported as successful, without actuall...
NSS 3.19.2.3 release notes
rg/security/nss/releases/nss_3_19_2_3_rtm/src/ new in nss 3.19.2.3 new functionality no new functionality is introduced in this release. security fixes in nss 3.19.2.3 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or
execution of arbitrary code with the permissions of the user. acknowledgements the nss development team would like to thank security researcher francis gabriel for responsibly disclosing the issue in bug 1245528. compatibility nss 3.19.2.3 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.19.2.3 s...
NSS 3.19.4 release notes
192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decoder used by nss for handling streaming ber data. while the majority of nss uses a separate, unaffected der decoder, several public routines also accept ber data, and thus are affected. an attacker that successfully exploited these issues can overflow the heap and may be able to obtain remote code
execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. because nss includes portions of the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss. bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow exceptionally large allocations to be reported as successful, without actuall...
NSS 3.20.1 release notes
192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decoder used by nss for handling streaming ber data. while the majority of nss uses a separate, unaffected der decoder, several public routines also accept ber data, and thus are affected. an attacker that successfully exploited these issues can overflow the heap and may be able to obtain remote code
execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. because nss includes portions of the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss. bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow exceptionally large allocations to be reported as successful, without actuall...
NSS 3.21.1 release notes
illa.org/security/nss/releases/nss_3_21_1_rtm/src/ new in nss 3.21.1 new functionality no new functionality is introduced in this release. security fixes in nss 3.21.1 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or
execution of arbitrary code with the permissions of the user. acknowledgements the nss development team would like to thank security researcher francis gabriel for responsibly disclosing the issue in bug 1245528. compatibility nss 3.21.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.21.1 share...
NSS 3.22.2 release notes
a.org/security/nss/releases/nss_3_22_2_rtm/src/ new in nss 3.22.2 new functionality no new functionality is introduced in this release. security fixes in nss 3.22.2 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or
execution of arbitrary code with the permissions of the user. notable changes in nss 3.22.2 bug 1247990 - the root ca changes from nss 3.23 have been backported. acknowledgements the nss development team would like to thank security researcher francis gabriel for responsibly disclosing the issue in bug 1245528. compatibility nss 3.22.2 shared libraries are backward compatible with all older nss 3...
NSS 3.23 release notes
ca sha-256 fingerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1:55:b3:7f:d7:60:66 security fixes in nss 3.23 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or
execution of arbitrary code with the permissions of the user. bugs fixed in nss 3.23 this bugzilla query returns all the bugs fixed in nss 3.23: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.23 acknowledgements the nss development team would like to thank security researcher francis gabriel for responsibly disc...
NSS sources building testing
tests" and start the tests using "./all.sh". the tests will take a while to complete; on a slow computer it could take a couple of hours. once the test suite has completed, a summary will be printed that shows the number of failures. you can find the test suite results in directory nss/../tests_results (i.e. the results directory ends up next to the nss directory, not within it). each test suite
execution will create a new subdirectory; you should clean them up from time to time. inside the directory you'll find text file output.log, which contains a detailed report of all tests being executed. in order to learn about the details of test failures, search the file for the uppercase test failed. if desired, it's possible to run only subsets of the tests. read the contents of file all.sh to learn ho...
Rhino documentation
ive includes release notes for rhino releases optimization details on the various optimization levels. faq answers to frequently asked questions about rhino. rhino history history of the beast. writing scripts scripting java how to use rhino to script java classes. performance hints some tips on writing faster javascript code. javascript tools rhino shell interactive or batch
execution of scripts. javascript debugger debugging scripts running in rhino. javascript compiler compiling scripts into java class files. running the rhino tests running the javascript test suite with rhino. embedding rhino embedding tutorial a short tutorial on how to embed rhino into your application. api javadoc reference (link broken? try this at jarvana.) an annotated outline of the pr...
Tutorial: Embedding Rhino
mand line: $ java runscript "math.cos(math.pi)" -1 $ java runscript "function f(x){return x+1} f(7)" 8 note that you'll have to have both the rhino classes and the runscript example class file in the classpath. let's step through the body of main one line at time. entering a context the code context cx = context.enter(); creates and enters a context. a context stores information about the
execution environment of a script. initializing standard objects the code scriptable scope = cx.initstandardobjects(); initializes the standard objects (object, function, etc.) this must be done before scripts can be executed. the null parameter tells initstandardobjects to create and return a scope object that we use in later calls. collecting the arguments this code is standard java and not specif...
Rhino Examples
xecutes javascript programs; it is a simplified version of the shell in the tools package. the programs may be specified as files on the command line or by typing interactively while the shell is running. primitivewrapfactory primitivewrapfactory.java is an example of a wrapfactory that can be used to control the wrapping behavior of the rhino engine on calls to java methods. multithreaded script
execution dynamicscopes.java is a program that creates a single global scope object and then shares it across multiple threads. sharing the global scope allows both information to be shared across threads, and amortizes the cost of context.initstandardobjects by only performing that expensive operation once. implementing host objects first check out the tutorial if you haven't already. the foo class - exte...
Rhino optimization
these features have been removed from the language in ecma, so higher optimization levels are now conformant. future versions may allocate more aggressive optimizations to higher optimization levels. for compatibility with future versions, use level 1. for maximal optimization, use level 9, but retest your application when upgrading to new versions. scripts are optimized at compile time, not at
execution time. so if a script is compiled with the context's optimizationlevel set to 1, it will be executed with those optimizations, regardless of the optimizationlevel of the context in which it is executed. ...
The JavaScript Runtime
compilation to java bytecodes for improved performance, rhino may compile javascript scripts to java bytecodes. the generated bytecodes in turn depend upon runtime support routines. ...
Bytecodes
also some slots reserved for dedicated functionality, holding values like this and the callee / return value. there is always a "top of stack" (tos) that corresponds to the latest value pushed onto the expression stack. all bytecodes implicitly operate in terms of this location. bytecode listing all opcodes are annotated with a [-popcount, +pushcount] to represent the overall stack-effects their
execution. bytecode listing was moved to spidermonkey internals: bytecode descriptions page. ...
Garbage collection
for marking, the gc does a series of short pauses. the pauses can be set to be 10ms or less. there is always a possibility that a long pause will be required. if the allocation rate is high during incremental gc, the engine may run out of memory before finishing the incremental gc. if so, the engine must immediately restart a full, non-incremental gc in order to reclaim some memory and continue
execution. incremental write barrier the problem that requires a write barrier incremental gc requires a write barrier for correctness. todo decent diagrams the basic problem is as follows (see dictionary for color terms). say object a is black and contains a pointer field. let object b be white. now let the incremental slice stop, so the mutator resumes. if the mutator stores b into a, so that a cont...
Property cache
365851. basics in general, accessing a property of a native object entails: a property lookup; examining the shape to see how the property can be accessed; actually carrying out the property access. the property cache is a per-thread cache of the results of steps 1 and 2. when executing certain property-accessing bytecode instructions, the interpreter populates the cache to speed future
execution of the same instruction. the jit reads the property cache too, as it needs the same information when recording such an instruction. if there is a cache miss, the jit performs parts 1 and 2 of the property access and fills the cache to avoid redoing that work in the interpreter. (in some cases this is necessary for correctness. when recording a getprop, the jit needs to know the result type befor...
SpiderMonkey Internals
l production. garbage collector the gc is a mark-and-sweep, non-conservative (exact) collector. it is used to hold js objects and string descriptors (jsstring), but not string bytes. it runs automatically only when maxbytes (as passed to js_newruntime) bytes of gc things have been allocated and another thing-allocation request is made. js api users should call js_gc or js_maybegc between script
executions or from the operation callback, as often as necessary. because the gc is exact, c/c++ applications must ensure that all live objects, strings, and numbers are gc-reachable. javascript values the type js::value represents a javascript value. the representation is 64 bits and uses nan-boxing on all platforms, although the exact nan-boxing format depends on the platform. nan-boxing is a techniq...
JIT Optimization Outcomes
this page documents the meaning of different optimization outcomes. general outcomes general outcomes shared between various optimization strategies. genericfailure the optimization attempt failed, and the reason was not recorded. genericsuccess optimization succeeded. disabled the optimization has been explicitly disallowed. ...
JS::Call
iled function. name const char * pointer to the function name to call. args js::handlevaluearray & arguments to pass to the function. rval js::mutablehandlevalue out parameter. on success, *rval receives the return value from the function call. description js::call calls a specified function, fun, on an object, thisobj. in terms of function
execution, the object is treated as this. for more detail, see js_callfunction, js_callfunctionname, and js_callfunctionvalue. see also mxr id search for js::call js_callfunction js_callfunctionname js_callfunctionvalue bug 601168 ...
JSErrorReport
an error report without any of the above flags. errornumber unsigned the error number. ucmessage const char16_t * the default unicode error message. messageargs const char16_t ** arguments for the error message. exntype int16_t one of the jsexntype constants. description jserrorreport describes a single error that occurs in the
execution of script. in the event of an error, filename will either contain the name of the external source file or url containing the script (script src=) or null, indicating that a script embedded in the current html page caused the error. lineno indicates the line number of the script containing the error. in the case of an error in a script embedded in the html page, lineno indicates the html lineno wh...
JSRuntime
represents an instance of the javascript engine. a program typically has only one jsruntime, even if it has many threads. the jsruntime is the universe in which javascript objects live; they can't travel to other jsruntimes. all javascript code and most jsapi calls run within a jscontext. the jscontext is a child of the jsruntime. a context can run scripts. it contains the global object and the
execution stack. exception handling, error reporting, and some language options are per-jscontext. once created, a context can be used any number of times for different scripts or jsapi queries. for example, a browser might create a separate context for each html page; every script in the page could use the same context. objects may be shared among jscontexts within a jsruntime. there's no fixed associati...
JS_CompileUTF8File
the context in which to compile the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object with which the script is associated. filename const char * name of file containing the script to compile. description js_compileutf8file compiles the text of script in an external file location for
execution by the js engine. filename is the name of the file containing the script to compile. on success, js_compileutf8file returns an object that represents the newly compiled script. otherwise it returns null. js_compileutf8file is deprecated, use file, use js::compile instead. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js_compilefile js::compi...
JS_CompileUTF8FileHandle
e of the file that contains the script, if available. file file * the file handle containing the script to compile. principals jsprincipals * (only in js_compileutf8filehandleforprincipals) the security principals to associate with the new script, or null. description js_compileutf8filehandle reads a script from a stdio file handle and compiles the script for
execution by the javascript engine. js_compileutf8filehandleforprincipals is a version of the function for use with spidermonkey's security features. filename is the name of the file containing the script to compile. file is the file handle. js_compileutf8filehandle does not close the file handle. if principals is non-null, it points to a jsprincipals object that is associated with the new script and any...
JS_ExecuteRegExp
this jscontext. obj js::handleobject a pointer to a global object. reobj js::handleobject a pointer to a regexp object. chars const char16_t * a pointer to the string contains a input string. length size_t the length of bytes or chars, in characters. indexp size_t * in/out parameter. a pointer to the lastindex for the
execution, and received the updated lastindex. test bool pass true to avoid creating match result array and store boolean value to rval. rval js::mutablehandlevalue out parameter. receives the result match result array or boolean value. description js_executeregexp and js_newregexpobjectnostatics execute the regexp object, reobj, to the specified input string, chars, fro...
JS_ExecuteScript
quest. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the scope in which to execute the script. in the simplest cases, this should just be the embedding's global object. obsolete since jsapi 39 obj must not be an array, an e4x xml object, a with object, or a proxy. in ecmascript terms, the script is executed in a new
execution context, but that context is not initialized quite as described in any of the three cases in ecma 262-3 §10.2. instead: the scope chain is initialized to contain obj, followed by its parent, then its parent's parent, etc. until null is reached. variable initialization is performed. if the jsoption_varobjfix option is in effect (recommended), then the last object in the scope chai...
JS_ExecuteScriptVersion
xecute the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * the scope in which to execute the script. in the simplest cases, this should just be the embedding's global object. obj must not be an array, an e4x xml object, a with object, or a proxy. in ecmascript terms, the script is executed in a new
execution context, but that context is not initialized quite as described in any of the three cases in ecma 262-3 §10.2. instead: the scope chain is initialized to contain obj, followed by its parent, then its parent's parent, etc. until null is reached. variable initialization is performed. if the jsoption_varobjfix option is in effect (recommended), then the last object in the scope chai...
JS_GetScopeChain
you can use the function js_getglobalforscopechain. syntax jsobject * js_getscopechain(jscontext *cx); name type description cx jscontext * the context to query. description js_getscopechain returns the first jsobject on the scope chain for the javascript code currently running in the given context, cx. the ecmascript standard, ecma 262-3 §10, describes
execution contexts and scope chains. a scope chain is a sequence of objects whose properties are searched whenever a script or function refers to a variable. these objects represent the lexical scope of the currently executing statement or expression, not the call stack, so they include: the variable objects of any enclosing functions or let statements or expressions, and any objects selected by enclosi...
JS_GetSecurityCallbacks
on which checks if a csp instance wants to disable eval() and friends. use null is not needed. subsumes jssubsumesop a pointe to the function which returns whether the first principal subsumes the second. use null is not needed. description js_setsecuritycallbacks sets the runtime's security callbacks to callbacks. it allows the embedding to control certain aspects of js code
execution based on security settings of the global object the code is executed in. if callbacks is null, it sets callbacks to default value. js_getsecuritycallbacks returns the runtime's current security callbacks. if the callbacks are default value, it returns null see also mxr id search for js_getsecuritycallbacks mxr id search for js_setsecuritycallbacks jsprincipals jscspevalchecker jssubsumesop bu...
JS_NewRegExpObject
rs const char * or const char16_t * a pointer to the string that contains a regular expression. length size_t the length of bytes or chars, in characters. flags unsigned regular expression flags. see below. flags name description regexp constructor flag jsreg_fold fold uppercase to lowercase. i jsreg_glob global
execution, creates array of matches. g jsreg_multiline treat ^ and $ as begin and end of line. m jsreg_sticky only match starting at lastindex. y description js_newregexpobject and js_newucregexpobject create a new regexp instance. the flags from the built-in regexp constructor properties ignorecase, global, multiline, and sticky are or'd in with the provided flags ...
JS_SetInterruptCallback
acks can occur inside the callback handler if it re-enters the js engine. the embedding must ensure that the callback is disconnected before attempting such re-entry. js_setinterruptcallback sets a callback that can be called asynchronously. some common uses for an interrupt callback are: to run garbage collection periodically, by calling js_maybegc; to periodically take a break from script
execution to update the ui (though note that mozilla does not do this, by design); to enforce application limits on the amount of time a script may run. (in this case, the callback may terminate the script by returning false.) js_getinterruptcallback returns the currently installed interrupt callback, or null if none is currently installed. js_requestinterruptcallback requests a callback set using js_s...
JS_SetOperationCallback
acks can occur inside the callback handler if it re-enters the js engine. the embedding must ensure that the callback is disconnected before attempting such re-entry. js_setoperationcallback sets a callback that can be called asynchronously. some common uses for an operation callback are: to run garbage collection periodically, by calling js_maybegc; to periodically take a break from script
execution to update the ui (though note that mozilla does not do this, by design); to enforce application limits on the amount of time a script may run. (in this case, the callback may terminate the script by returning js_false.) js_getoperationcallback returns the currently installed operation callback, or null if none is currently installed. js_triggeroperationcallback triggers a callback set using j...
JS_SetOptions
(see nsisupports). this is only meaningful if spidermonkey is built with xpconnect. mxr id search for jsoption_private_is_nsisupports jsoption_compile_n_go caller of js_compilescript et al promises to execute the compiled script once only, in the same scope object used for compilation. the caller may not modify objects on the scope chain between compilation and
execution. this enables compile-time scope chain resolution of consts (a performance optimization). mxr id search for jsoption_compile_n_go jsoption_atline //@line number ["filename"] option supported for the xul preprocessor and kindred beasts. mxr id search for jsoption_atline jsoption_xml obsolete since jsapi 15 ecmascript for xml (e4x...
JS_SetScriptStackQuota
the desired stack quota setting, in bytes. description set the quota on the number of bytes that stack-like data structures can use when the runtime compiles and executes scripts. these structures also consume heap space, so js_setthreadstacklimit does not bound their size. the default quota is 32mb which is quite generous. the function must be called before any script compilation or
execution api calls, i.e. either immediately after js_newcontext or from the jscontext_new context callback. see also mxr id search for js_setscriptstackquota bug 644241 ...
SpiderMonkey 1.8.5
rvative gc for cases where the compiler might optimize away important stack/register roots (such as when we access the jschars in a jsstring). a c analogue, js_anchorptr, was introduced with bug 630209. bug 630209 also removed the need for js_newscriptobject, by modifying the script compilation interfaces to handle the creation and management of the object wrapper directly; similarly, the script
execution interfaces now accept a jsobject pointer than a pointer to jsscript. affected interfaces are: js_compilescript js_compilescriptforprincipals js_compilescriptforprincipalsversion js_compileucscript js_compileucscriptforprincipals js_compileucscriptforprincipalsversion js_compilefile js_compilefilehandle js_compilefilehandleforprincipals js_compilefilehandleforprincipalsversion js_compi...
SpiderMonkey 1.8.7
vative gc for cases where the compiler might optimize away important stack/register roots (such as when we access the jschars in a jsstring). a c analogue, js_anchorptr, was introduced with bug 630209. bug 630209 also removed the need for js_newscriptobject, by modifying the script compilation interfaces to handle the creation and management of the object wrapper directly; similarly, the script
execution interfaces now accept a jsobject pointer than a pointer to jsscript. affected interfaces are: js_compilescript js_compilescriptforprincipals js_compilescriptforprincipalsversion js_compileucscript js_compileucscriptforprincipals js_compileucscriptforprincipalsversion js_compilefile js_compilefilehandle js_compilefilehandleforprincipals js_compilefilehandleforprincipalsversion js_compi...
SavedFrame
younger frames hold a reference to the frames that invoked them. the older tails are shared across many younger frames. savedframe stacks should generally be captured, allocated, and live within the compartment that is being observed or debugged. usually this is a content compartment. capturing savedframe stacks from c++ use js::capturecurrentstack declared in jsapi.h. from js use savestack, accessible via components.utils.getjstestingfunction(). ...
WebReplayRoadmap
lysis features an important but as-yet unexploited advantage of being able to exactly replay a web replay recording is that the recording can be analyzed without overhead affecting the user's experience. this section describes some analyses that could be performed and be helpful for developers who are either debugging a problem, or trying to understand or improve a complex code base. comparing
executions (not yet implemented) comparing the behavior of a recording that exhibits a bug with a second recording that doesn't exhibit the bug should help with quickly locating the source of the problem. doing this well will require some experimentation, but in many cases the buggy recording should hit different locations in the source or exhibit different types from the normal recording. using a corpu...
Redis Tips
c(function(err, results) { /** * if err is null, it means redis successfully attempted * the operation. */ if(err) throw err; /** * if results === null, it means that a concurrent client * changed the key while we were processing it and thus * the
execution of the multi command was not performed. * * notice: failing an
execution of multi is not considered * an error. so you will have err === null and results === null */ }); }); }); nice. you just have to be careful that you check the result type of an exec() when you're watching variables. it could be either a li...
Secure Development Guidelines
.st_uid != getuid) { bailout(“you don’t own the file”); } fd = open(file, o_rdwr); write(fd, argv[2], strlen(argv[2])); } file i/o: race conditions previous example contains a race condition the file may change between the call top stat() and open() this opens the possibility of writing arbitrary content to any file race conditions occur when two separate
execution flows share a resource and its access is not synchronized properly race condition types include file (previously covered) thread (two threads share a resource but don’t lock it) signal race conditions example char *ptr; void sighandler() { if (ptr) free(ptr); _exit(0); } int main() { signal(sigint, sighandler); ptr = malloc(1000); ...
Finishing the Component
teger, 10. this works fine in any gecko installation where a contract guarantees that the interface that was compiled against has the same signature. however, when this same component is used in a gecko installation where this interface has changed, the method testa does not exist in the nsifoo interface; the first entry in the v-table is in fact isprime(). when this method call is made, the code
execution treats the isprime method as testa. needless to say, this is a bad thing. furthermore, there is no way easy way to realize this error at runtime. gecko developers could change the interface's iid, and some do. this can prevent many errors like this. but unfrozen interfaces are not supported in any formal way, and relying upon a different iid for any change in the interface is not a good idea e...
Making cross-thread calls using runnables
layout, dom operations, content javascript, and chrome javascript run on the main thread. however, it may be useful for c++ code in the mozilla platform to run tasks on another thread. typically, thread activities are triggered and managed using an xpcom event-passing framework that uses the nsirunnable interface. each runnable represents a task which can then be dispatched to another thread for
execution. note: javascript code cannot use the techniques described in this article. chrome javascript should instead use workers. in general, threading and message passing should be asynchronous. for example, let's say we have a function, calculatepi(int digits), which will calculate π to an arbitrary number of digits: void calculatepi(int digits, nscstring& result); // this is synchronous this can t...
Components.utils.Sandbox
of gecko 13 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10), if you don't specify a sandbox name it will default to the caller's filename. sandboxprototype a prototype object for the sandbox. the sandbox will inherit the contents of this object if it's provided. passing a content window object, setting wantxrays:true (default) and using an extended principal provides a clean, isolated
execution environment in which javascript code that needs web apis (such as accessing the window's dom) can be executed without interference from untrusted content code. wantcomponents a boolean indicating whether the components object is available or not in the sandbox. default: true. if the sandbox interacts with untrusted content this should be set to false when possible to further reduce possi...
Components.utils.reportError
lt. to show them, set the preference 'javascript.options.showinconsole' to true, or use nsconsoleservice instead to show a message. ...
mozIStorageAsyncStatement
an asynchronous sql statement. this differs from mozistoragestatement by only being usable for asynchronous
execution. (mozistoragestatement can be used for both synchronous and asynchronous purposes.) this specialization for asynchronous operation allows us to avoid needing to acquire synchronization primitives also used by the asynchronous
execution thread. in contrast, mozistoragestatement may need to acquire the primitives and consequently can cause the main thread to lock for extended intervals while the asynchronous thread performs some long-running operation. inherited interface mozistoragebasestatement ...
mozIStorageProgressHandler
storage/public/mozistorageprogresshandler.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports method overview boolean onprogress(in mozistorageconnection aconnection); methods onprogress() the onprogress() method is called periodically while an sqlite operation is ongoing. this allows you to monitor the progress and possibly display status information to the user. ...
mozIStorageValueArray
se. see also storage introduction and how-to article mozistorageconnection database connection to a specific file or in-memory data storage mozistoragestatement create and execute sql statements on a sqlite database. mozistoragefunction create a new sqlite function. mozistorageaggregatefunction create a new sqlite aggregate function. mozistorageprogresshandler monitor progress during the
execution of a statement. mozistoragestatementwrapper storage statement wrapper ...
nsIDOMWindowUtils
ndow.setresolution(2.0, 2.0); // elsewhere browser.setviewportscale(2.0, 2.0); the caller of this method must have universalxpconnect privileges. void setresolution( in float axresolution, in float ayresolution ); parameters axresolution ayresolution startpccountprofiling() begins detailed profiling of all executed javascript code in the browser. this slows down javascript
execution, but accumulates information about what code has executed that may be queried after a call to stoppccountprofiling(). void startpccountprofiling(); parameters none. stoppccountprofiling() stops profiling of executed javascript code. profile information about code that has executed since a preceding call to startpccountprofiling() will be constructed, and will be retained until a call to...
nsIDocShell
llowdnsprefetch boolean attribute that determines whether dns prefetch is allowed for this subtree of the docshell tree. defaults to true. setting this will make it take effect starting with the next document loaded in the docshell. allowimages boolean attribute stating whether or not images should be loaded. allowjavascript boolean whether to allow javascript
execution. allowmedia boolean attribute stating whether or not media (audio/video) should be loaded. allowmetaredirects boolean attribute stating if refresh based redirects can be allowed. allowplugins boolean whether to allow plugin
execution. allowsubframes boolean attribute stating if it should allow subframes (framesets/iframes) or not. ...
nsIEventListenerInfo
bject if the debug service is active. nsisupports getdebugobject(); parameters none. return value if jsdidebuggerservice is active and the listener is implemented in js, this returns the listener as a jsdivalue. otherwise null. this is the method you should use if you want to get access to the actual listener, but the debugger service must be already active, which significantly slows down script
execution. accordingly, this should probably only be used by real debuggers. this approach is necessary because event listeners added with addeventlistener won't necessarily be nsieventlisteners; the dom code will fix up ordinary javascript functions to act as listeners. tosource() tries to serialize the event listener to a string. astring tosource(); parameters none. return value returns a string describ...
nsIInputStream
m: nsisupports last changed in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) an input stream may be "blocking" or "non-blocking" (see the isnonblocking() method). a blocking input stream may suspend the calling thread in order to satisfy a call to close(), available(), read(), or readsegments(). a non-blocking input stream, on the other hand, must not block the calling thread of
execution. note: blocking input streams are often read on a background thread to avoid locking up the main application thread. for this reason, it is generally the case that a blocking input stream should be implemented using thread-safe addref and release. method overview unsigned long available();deprecated since gecko 17.0 unsigned long long available(); void close(); ...
nsIOutputStream
table stream of data. inherits from: nsisupports last changed in gecko 1.0 an output stream may be "blocking" or "non-blocking" (see the isnonblocking() method). a blocking output stream may suspend the calling thread in order to satisfy a call to close(), flush(), write(), writefrom(), or writesegments(). a non-blocking output stream, on the other hand, must not block the calling thread of
execution. note: blocking output streams are often written to on a background thread to avoid locking up the main application thread. for this reason, it is generally the case that a blocking output stream should be implemented using thread-safe addref and release. method overview void close(); void flush(); boolean isnonblocking(); unsigned long write(in string abuf,...
nsIRunnable
nsirunnable is generated from nsirunnable.idl here is the prototype of nsirunnable.idl /** * represents a task which can be dispatched to a thread for
execution. */ interface nsirunnable : nsisupports { /** * the function implementing the task to be run. */ void run(); }; ...
nsISupports proxies
the main reason for nsisupports proxies is that javascript and ui are on a single thread. when one is busy, the other is blocked. a good example of this is the old install.js scripts that were used in xpinstall in older mozilla versions. they from the majority of javascript code, which is small and can be quickly run. xpinstall installation scripts are sometimes very complex and can require long
execution time due to unzipping or native file system actions. if xpinstall ran on the ui thread, the product would appear frozen until the script was complete. this is definitely bad. because of this, xpinstall was moved to its own thread. now xpinstall can do its installations while the product renders, but now xpinstall can not access ui elements such as a progress meter or a confirmation dialog. how ca...
nsIThread
es attribute type description prthread prthread the nspr thread object corresponding to the nsithread. read only. methods shutdown() shuts down the thread. this causes events to stop being dispatched to the thread, and causes any pending events to run to completion before the thread joins with the current thread (see pr_jointhread() for details). during the
execution of this method call, events for the current thread may continue to be processed. warning: this method may not be called from the thread itself. instead, you must only call it from another thread (usually the thread that created it, or the main application thread). when this function returns, the thread will be shut down and will no longer be available to receive events. void shutdown() ...
nsMsgRuleActionType
g custom=-1; /* see nsmsgfilteraction */ const long none=0; /* uninitialized state */ const long movetofolder=1; const long changepriority=2; const long delete=3; const long markread=4; const long killthread=5; const long watchthread=6; const long markflagged=7; const long label=8; const long reply=9; const long forward=10; const long stop
execution=11; const long deletefrompop3server=12; const long leaveonpop3server=13; const long junkscore=14; const long fetchbodyfrompop3server=15; const long copytofolder=16; const long addtag=17; const long killsubthread=18; const long markunread=19; }; ...
Testing Mozilla code
resent the build-time static-analysis.debugging mozilla with valgrindthis page describes how to use valgrind (specifically, its memcheck tool) to find memory errors.firefox and address sanitizeraddress sanitizer (asan) is a fast memory error detector that detects use-after-free and out-of-bound bugs in c/c++ programs. it uses a compile-time instrumentation to check all reads and writes during the
execution. in addition, the runtime part replaces the malloc and free functions to check dynamically allocated memory. more information on how asan works can be found on the address sanitizer wiki. fuzzing interfacethe fuzzing interface is glue code living in mozilla-central in order to make it easier for developers and security researchers to test c/c++ code with either libfuzzer or afl-fuzz.measuring...
Detect Opening Folder
some actions require
execution every time you open a folder (for example, registering a custom column handler. to do this you need to capture the select event of the folder [[xul:tree|tree]] whose id is (conveniently) foldertree like so: window.document.getelementbyid('foldertree').addeventlistener("select", testcolumns, false); ...
Using the Mozilla symbol server
d firefox releases from 2.0.0.4. this allows debugging of those builds without forcing all users to download large debugging files. the server functions like microsoft's symbol server so the documentation there can be useful. note that because mozilla release builds are heavily optimized, debugging is not always easy. the debugger will not be able to show you the content of all variables and the
execution path can seem strange because of inlining, tail calls, and other compiler optimizations. the only workaround is to build an unoptimized local build. the official symbol server url for firefox is https://symbols.mozilla.org/. you cannot visit this url directly: you must add it to the symbol path of your debugging tool. in the examples below, a local cache directory is used to avoid repeatedly fet...
Debug worker threads - Firefox Developer Tools
d logpoints just as you can with javascript code running on the main thread. inspecting worker code for example, see the selected item worker.js below — it is listed in a separate thread in the sources list, but appears in the source pane in the same way as main thread code when selected. setting breakpoints, etc. you can set a breakpoint (or logpoint) on any active worker thread: when
execution is paused in a worker thread, the context of the debugger is updated to show the correct breakpoints, call stack, etc., just as you'd expect. ...
Examine, modify, and watch variables - Firefox Developer Tools
(optimized away), and is not editable. in the screenshot below the variable upvar has been optimized away: modify variables when the code has stopped at a breakpoint, you can modify variables in the variables pane of the debugger. just click on the variable's current value and you'll be able to type there: watch an expression watch expressions are expressions that are evaluated each time
execution pauses. you can then examine the results of these expressions. these are useful in that they let you inspect invariants in your code that you know are there but aren't necessarily in the code ready for inspection. to add a watch expression, click in the box that says "add watch expression" and enter a javascript expression whose output you'd like to monitor as you step through code. then start r...
Set watch expressions - Firefox Developer Tools
the debugger features a pane for entering expressions to be watched (watch expressions). as you step through code, the debugger will watch the expression and return any results. to set a watch expression, expand the watch expressions sidebar, then click "add watch expression." type the expression you'd like to watch into the text field. the debugger will save the expression and watch it as you step through your code. when the debugger reaches a breakpoint, it will display your watch expressions variables: you can step through your code, watching the value of the expression as it changes. ...
Step through code - Firefox Developer Tools
in the toolbar: in order, the buttons are: play: run to the next breakpoint step over: advance to the next line in the same function. step in: advance to the next line in the function, unless on a function call, in which case enter the function being called step out: run to the end of the current function, in which case, the debugger will skip the return value from a function, returning
execution to the caller split console when paused, you can press the esc key to open and close the split console to gain more insight into errors and variables: pause on breakpoints overlay since firefox 70, when your code is paused on a breakpoint an overlay appears on the viewport of the tab you are debugging. this lets you know what kind of breakpoint the code is paused on (breakpoint, event...
Use watchpoints - Firefox Developer Tools
an object you want to watch, and right-click it to open its context menu. choose break on, and then one of property set property get property get or set a watchpoint icon appears to the right of the property in the scopes pane. set watchpoint icons are blue, get watchpoint icons are reddish, and get or set watchpoint icons are dark yellow. click play or press f8 to resume
execution. view a watchpoint when the watched property is accessed in the way specified by the watchpoint type (get or set), the debugger pauses, enabling you to see line of code responsible, and to inspect anything else you wish at that time. in the following screenshot, the debugger pauses at line 7, where obj.a is set. the message panel in the upper right corner indicates that the debugger is "pause...
Debugger keyboard shortcuts - Firefox Developer Tools
close current file ctrl + w cmd + w ctrl + w search for a string in the current file ctrl + f cmd + f ctrl + f search for a string in all files ctrl + shift + f cmd + shift + f ctrl + shift + f find next in the current file ctrl + g cmd + g ctrl + g search for scripts by name ctrl + p cmd + p ctrl + p resume
execution when at a breakpoint f8 f8 1 f8 step over f10 f10 1 f10 step into f11 f11 1 f11 step out shift + f11 shift + f11 1 shift + f11 toggle breakpoint on the currently selected line ctrl + b cmd + b ctrl + b toggle conditional breakpoint on the currently selected line ctrl + shift + b cmd + shift + b ctrl...
Set an XHR breakpoint - Firefox Developer Tools
an xhr (xmlhttprequest) breakpoint breaks code
execution when an xhr request is dispatched so that you can examine the current state of the program. you can break on all requests or on those that include a specific url. to turn on the feature: open the debugger click on "pause on any url" which acts as a wild card, causing the code to pause on any call, or, click the plus sign next to the xhr breakpoints header, enter the url in which you are interested, and press enter. note: if you enter a key word instead of a url, code
execution will pause on any call to a url that contains that keyword. when your code breaks on an xhr request, the righthand pane will have two additional sections: call stack the list of functions that were executed in order ot get to the currently executing cod...
Debugger.Environment - Firefox Developer Tools
does not include the names of identifiers bound by enclosing environments. getvariable(name) return the value of the variable bound toname in this environment, or undefined if this environment does not bindname.name must be a string that is a valid ecmascript identifier name. the result is a debuggee value. javascript engines often omit variables from environments, to save space and reduce
execution time. if the given variable should be in scope, but getvariable is unable to produce its value, it returns an ordinary javascript object (not a debugger.object instance) whose optimizedout property is true. this is not an invocation function; if this call would cause debuggee code to run (say, because the environment is a "with" environment, andname refers to an accessor property of the with st...
Debugger.Memory - Firefox Developer Tools
kecensus to conduct a census of its debuggees’ possessions. accessor properties of the debugger.memory.prototype object ifdbg is a debugger instance, then <i>dbg</i>.memory is a debugger.memory instance, which inherits the following accessor properties from its prototype: trackingallocationsites a boolean value indicating whether this debugger.memory instance is capturing the javascript
execution stack when each object is allocated. this accessor property has both a getter and setter: assigning to it enables or disables the allocation site tracking. reading the accessor produces true if the debugger is capturing stacks for object allocations, and false otherwise. allocation site tracking is initially disabled in a new debugger. assignment is fallible: if the debugger cannot track alloca...
Debugger.Script - Firefox Developer Tools
t children are included; nested children can be reached by walking the tree. if the instance refers to webassembly code, throw a typeerror. setbreakpoint(offset,handler) if the instance refers to a jsscript, set a breakpoint at the bytecode instruction atoffset in this script, reporting hits to the hit method ofhandler. ifoffset is not a valid offset in this script, throw an error. when
execution reaches the given instruction, spidermonkey calls the hit method ofhandler, passing a debugger.frame instance representing the currently executing stack frame. the hit method’s return value should be a resumption value, determining how
execution should continue. any number of breakpoints may be set at a single location; when control reaches that point, spidermonkey calls their handlers in an ...
All keyboard shortcuts - Firefox Developer Tools
close current file ctrl + w cmd + w ctrl + w search for a string in the current file ctrl + f cmd + f ctrl + f search for a string in all files ctrl + shift + f cmd + shift + f ctrl + shift + f find next in the current file ctrl + g cmd + g ctrl + g search for scripts by name ctrl + p cmd + p ctrl + p resume
execution when at a breakpoint f8 f8 1 f8 step over f10 f10 1 f10 step into f11 f11 1 f11 step out shift + f11 shift + f11 1 shift + f11 toggle breakpoint on the currently selected line ctrl + b cmd + b ctrl + b toggle conditional breakpoint on the currently selected line ctrl + shift + b cmd + shift + b ctrl...
UI Tour - Firefox Developer Tools
rrently selected. to switch to a different tool, use the buttons in the toolbar. waterfall the waterfall presents a view of the work the browser is doing during the recording: executing javascript, updating the css, updating the page layout, and performing repaints. the x-axis represents time, and the recorded operations are laid out as a waterfall, reflecting the serial nature of the browser's
execution. to learn much more about the waterfall, see the separate waterfall page. call tree the call tree is a sampling profiler for javascript running in the page. it periodically samples the state of the javascript engine, and records the stack for the code executing at the time the sample was taken. statistically, the number of samples taken in which we were executing a particular function corres...
Waterfall - Firefox Developer Tools
n time, the browser is doing one of those things. so if you see a sign of a performance problem - a drop in the frame rate, for example - you can go to the waterfall to see what the browser was doing at that point in the recording. along the x-axis is time. recorded operations, called markers, are shown as horizontal bars, laid out in a waterfall to reflect the serial nature of the browser's
execution. when a marker is selected you'll see more information about it in a sidebar on the right. this includes the marker's duration and some more information that's specific to the marker type. markers the markers for operations are color-coded and labeled. the following operations are recorded: name and description color detailed information dom event javascr...
Web Console remoting - Firefox Developer Tools
s if the string is very long. console api messages the window.console api calls send internal messages throughout gecko which allow us to do whatever we want for each call. the web console actor sends these messages to the remote debugging client. we use the objectactor from dbg-script-actors.js without a threadactor, to avoid slowing down the page scripts - the debugger deoptimizes javascript
execution in the target page. the lifetime of object actors in the web console is different than the lifetime of these objects in the debugger - which is usually per pause or per thread. the web console manages the lifetime of objectactors manually. prior to firefox 23 we used a different actor (webconsoleobjectactor) for working with javascript objects through the protocol. in bug 783499 we did a number...
AudioContext - Web APIs
you need to create an audiocontext before you do anything else, as everything happens inside a context. it's recommended to create one audiocontext and reuse it instead of initializing a new one each time, and it's ok to use a single audiocontext for several different audio source and pipeline concurrently. ...
AudioWorklet - Web APIs
access the audio context's instance of audioworklet through the baseaudiocontext.audioworklet property. ...
AudioWorkletProcessor.process - Web APIs
e (see audioworkletnodeoptions). if there is no active node connected to the n-th input of the node, inputs[n] will be an empty array (zero input channels available). the number of channels in each input may vary, depending on channelcount and channelcountmode properties. outputs an array of outputs that is similar to the inputs parameter in structure. it is intended to be filled during the
execution of the process() method. each of the output channels is filled with zeros by default — the processor will output silence unless the output arrays are modified. parameters an object containing string keys and float32array values. for each custom audioparam defined using the parameterdescriptors getter, the key in the object is a name of that audioparam, and the value is a float32array. the v...
BaseAudioContext.createBuffer() - Web APIs
which can then be populated by data, and played via an audiobuffersourcenode for more details about audio buffers, check out the audiobuffer reference page. note: createbuffer() used to be able to take compressed data and give back decoded samples, but this ability was removed from the spec, because all the decoding was done on the main thread, therefore createbuffer() was blocking other code
execution. the asynchronous method decodeaudiodata() does the same thing — takes compressed audio, say, an mp3 file, and directly gives you back an audiobuffer that you can then set to play via in an audiobuffersourcenode. for simple uses like playing an mp3, decodeaudiodata() is what you should be using. syntax var buffer = baseaudiocontext.createbuffer(numofchannels, length, samplerate); parameters...
BluetoothDevice - Web APIs
the bluetoothdevice interface of the web bluetooth api represents a bluetooth device inside a particular script
execution environment. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30...
BluetoothRemoteGATTServer - Web APIs
boolean connected; promise<bluetoothremotegattserver> connect(); void disconnect(); promise<bluetoothremotegattservice> getprimaryservice(bluetoothserviceuuid service); promise<sequence<bluetoothremotegattservice>> getprimaryservices(optional bluetoothserviceuuid service); }; properties bluetoothremotegattserver.connectedread only a boolean value that returns true while this script
execution environment is connected to this.device. it can be false while the user agent is physically connected. bluetoothremotegattserver.deviceread only a reference to the bluetoothdevice running the server. methods bluetoothremotegattserver.connect() causes the script
execution environment to connect to this.device. bluetoothremotegattserver.disconnect() causes the script
execution environmen...
CSS Painting API - Web APIs
the api defines paintworklet, a worklet that can be used to programmatically generate an image that responds to computed style changes. to find out more about how this is used, consult using the css painting api. interfaces paintworklet programmatically generates an image where a css property expects a file. access this interface through css.paintworklet. paintworkletglobalscope the global
execution context of the paintworklet. paintrenderingcontext2d implements a subset of the canvasrenderingcontext2d api. it has an output bitmap that is the size of the object it is rendering to. paintsize returns the read-only values of the output bitmap's width and height. dictionaries paintrenderingcontext2dsettings a dictionary providing a subset of canvasrenderingcontext2d settings. exa...
DedicatedWorkerGlobalScope - Web APIs
the worker's scope. you can specify as many as you'd like, separated by commas. for example: importscripts('foo.js', 'bar.js'); implemented from other places windowbase64.atob() decodes a string of data which has been encoded using base-64 encoding. windowbase64.btoa() creates a base-64 encoded ascii string from a string of binary data. windowtimers.clearinterval() cancels the repeated
execution set using windowtimers.setinterval(). windowtimers.cleartimeout() cancels the repeated
execution set using windowtimers.settimeout(). windowtimers.setinterval() schedules the
execution of a function every x milliseconds. windowtimers.settimeout() sets a delay for executing a function. events message fired when the worker receives a message from its parent. also available via the onm...
Element: error event - Web APIs
bubbles no cancelable no interface event or uievent event handler property onerror the event object is a uievent instance if it was generated from a user interface element, or an event instance otherwise. ...
Element - Web APIs
el fires on a <dialog> when the user instructs the browser that they wish to dismiss the current open dialog. for example, the browser might fire this event when the user presses the esc key or clicks a "close dialog" button which is part of the browser's ui. also available via the oncancel property. error fired when a resource failed to load, or can't be used. for example, if a script has an
execution error or an image can't be found or is invalid. also available via the onerror property. scroll fired when the document view or an element has been scrolled. also available via the onscroll property. select fired when some text has been selected. also available via the onselect property. show fired when a contextmenu event was fired on/bubbled to an element that has a contextmenu attribu...
Event.currentTarget - Web APIs
ppear note: the value of event.currenttarget is only available while the event is being handled. if you console.log() the event object, storing it in a variable, and then look for the currenttarget key in the console, its value will be null. instead, you can either directly console.log(event.currenttarget) to be able to view it in the console or use the debugger statement, which will pause the
execution of your code thus showing you the value of event.currenttarget. specifications specification status comment domthe definition of 'event.currenttarget' in that specification. living standard dom4the definition of 'event.currenttarget' in that specification. obsolete document object model (dom) level 3 events specificationthe definition of ...
FeaturePolicy.features() - Web APIs
syntax const supportedfeatures = featurepolicy.features() parameters none. return value a list of strings that represent names of all feature policy directives supported by the user agent. ...
Using the Gamepad API - Web APIs
s ? navigator.webkitgetgamepads : []); for (var i = 0; i < gamepads.length; i++) { var gp = gamepads[i]; if (gp) { gamepadinfo.innerhtml = "gamepad connected at index " + gp.index + ": " + gp.id + ". it has " + gp.buttons.length + " buttons and " + gp.axes.length + " axes."; gameloop(); clearinterval(interval); } } } now on to the main game loop. in each
execution of the loop we check if one of four buttons is being pressed; if so, we update the values of the a and b movement variables appropriately, then update the left and top properties, changing their values to the current values of a and b respectively. this has the effect of moving the ball around the screen. in current versions of chrome (version 34 as of this writing) the button values are stored ...
InstallTrigger - Web APIs
imple installations, the install methods on the installtrigger object may be all that's needed in the installation script. for more complex installations, you may need to use the install and/or file installation objects. in either case, you must trigger the installation process by creating a web page script in which installtrigger methods download the specified xpi file and "trigger" the
execution of the install.js script at the top level of that xpi. the principal method on the installtrigger object is install, which downloads and installs one or more software packages archived in the xpi file format. the following is a basic example of an install trigger on a web page: xpi={'xpinstall dialog display name':'simple.xpi'}; installtrigger.install(xpi); you can also use ...
Long Tasks API - Web APIs
of the task. usage var observer = new performanceobserver(function(list) { var perfentries = list.getentries(); for (var i = 0; i < perfentries.length; i++) { // process long task notifications: // report back for analytics and monitoring // ... } }); // register observer for long task notifications observer.observe({entrytypes: ["longtask"]}); // long script
execution after this will result in queueing // and receiving "longtask" entries in the observer. interfaces performancelongtasktiming reports instances of long tasks. taskattributiontiming returns information about the work involved in a long task and its associate frame context. specifications specification status comment long tasks api 1 working draft initial def...
Node - Web APIs
syntax eachnode(rootnode, callback) description recursively calls a function for each descendant node of rootnode (including the root itself). if callback is omitted, the function returns an array instead, which contains rootnode and all nodes contained within. if callback is provided, and it returns boolean false when called, the current recursion level is aborted, and the function resumes
execution at the last parent's level. this can be used to abort loops once a node has been found (such as searching for a text node which contains a certain string). parameters rootnode the node object whose descendants will be recursed through. callback optional an optional callback function that receives a node as its only argument. if omitted, eachnode returns an array of every node contained wit...
SVGElement - Web APIs
nts using addeventlistener() or by assigning an event listener to the equivalent on... handler property defined on globaleventhandlers or windoweventhandlers. abort fired when page loading is stopped before an svg element has been allowed to load completely. also available via the onabort property. error fired when an svg element does not load properly or when an error occurs during script
execution. also available via the onerror property. load fires on an svgelement when it is loaded in the browser. also available via the onload property. resize fired when an svg document is being resized. also available via the onresize property. scroll fired when an svg document view is being shifted along the x and/or y axes. also available via the onscroll property. unload fired when the do...
ServiceWorkerContainer.ready - Web APIs
it returns a promise that will never reject, and which waits indefinitely until the serviceworkerregistration associated with the current page has an active worker. once that condition is met, it resolves with the serviceworkerregistration. syntax navigator.serviceworker.ready.then(function(serviceworkerregistration) { ... }); value a promise that will never reject, and which may eventually resolve with a serviceworkerregistration. ...
ServiceWorkerContainer - Web APIs
nt page is actively controlled. properties serviceworkercontainer.controller read only returns a serviceworker object if its state is activated (the same object returned by serviceworkerregistration.active). this property returns null during a force-refresh request (shift + refresh) or if there is no active worker. serviceworkercontainer.ready read only provides a way of delaying code
execution until a service worker is active. it returns a promise that will never reject, and which waits indefinitely until the serviceworkerregistration associated with the current page has an serviceworkerregistration.active worker. once that condition is met, it resolves with the serviceworkerregistration. events controllerchange occurs when the document's associated serviceworkerregistration acqu...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
d with clients.claim() to ensure that updates to the underlying service worker take effect immediately for both the current client and all other active clients. syntax serviceworkerglobalscope.skipwaiting().then(function() { //do something }); returns a promise that immediately resolves with undefined. example while self.skipwaiting() can be called at any point during the service worker's
execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the waiting state. therefore, it's common to call self.skipwaiting() from inside of an installevent handler. the following example causes a newly installed service worker to progress into the activating state, regardless of whether there is already an active service worker. self.addeventliste...
ServiceWorkerGlobalScope - Web APIs
developers should keep in mind that the serviceworker state is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state. once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. an active service worker is automatically restarted to respond to events, such as serviceworkerglobalscope.onfetch or serviceworkerglobalscope.onmessage. ...
Using Service Workers - Web APIs
onsidered a secure origin by browsers as well. basic architecture with service workers, the following steps are generally observed for basic set up: the service worker url is fetched and registered via serviceworkercontainer.register(). if successful, the service worker is executed in a serviceworkerglobalscope; this is basically a special kind of worker context, running off the main script
execution thread, with no dom access. the service worker is now ready to process events. installation of the worker is attempted when service worker-controlled pages are accessed subsequently. an install event is always the first one sent to a service worker (this can be used to start the process of populating an indexeddb, and caching site assets). this is really the same kind of procedure as installing...
Service Worker API - Web APIs
ntexts (e.g. pages, workers, etc.) can be associated with the same serviceworker object. serviceworkercontainer provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister, and update service workers, and access the state of service workers and their registrations. serviceworkerglobalscope represents the global
execution context of a service worker. serviceworkermessageevent represents a message sent to a serviceworkerglobalscope. note that this interface is deprecated in modern browsers. service worker messages will now use the messageevent interface, for consistency with other web messaging features. serviceworkerregistration represents a service worker registration. serviceworkerstate associated wi...
SharedWorkerGlobalScope - Web APIs
the worker's scope. you can specify as many as you'd like, separated by commas. for example: importscripts('foo.js', 'bar.js'); implemented from other places windowbase64.atob() decodes a string of data which has been encoded using base-64 encoding. windowbase64.btoa() creates a base-64 encoded ascii string from a string of binary data. windowtimers.clearinterval() cancels the repeated
execution set using windowtimers.setinterval(). windowtimers.cleartimeout() cancels the repeated
execution set using windowtimers.settimeout(). windowtimers.setinterval() schedules the
execution of a function every x milliseconds. windowtimers.settimeout() sets a delay for executing a function. events listen to this event using addeventlistener() or by assigning an event listener to the oneventnam...
Transferable - Web APIs
this is an abstract interface and there is no object of this type. this interface does not define any method or property; it is merely a tag indicating objects that can be used in specific conditions, such as being transfered to a worker using the worker.postmessage() method. note: the transferable interface technically no longer exists. the functionality of transferable objects still exists, however, but is implemented at a more fundamental level (technically speaking, using the [transferable] webidl extended attribute). ...
WebGL2RenderingContext.clientWaitSync() - Web APIs
dicating the sync object's status. gl.already_signaled: indicates that the sync object was signaled when this method was called. gl.timeout_expired: indicates that the timeout time passed and that the sync object did not become signaled. gl.condition_satisfied: indicates that the sync object was signaled before the timeout expired. gl.wait_failed: indicates that an error occurred during the
execution. examples var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); var status = gl.clientwaitsync(sync, 0, 0); specifications specification status comment webgl 2.0the definition of 'clientwaitsync' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glclientwaitsync' in that specification. standard ...
WebGLRenderingContext.finish() - Web APIs
syntax void gl.finish(); parameters none. return value none. specifications specification status comment webgl 1.0the definition of 'finish' in that specification. recommendation initial definition. ...
WebGLRenderingContext - Web APIs
attribpointer() specifies the data formats and locations of vertex attributes in a vertex attributes array. drawing buffers webglrenderingcontext.clear() clears specified buffers to preset values. webglrenderingcontext.drawarrays() renders primitives from array data. webglrenderingcontext.drawelements() renders primitives from element array data. webglrenderingcontext.finish() blocks
execution until all previously called commands are finished. webglrenderingcontext.flush() empties different buffer commands, causing all commands to be executed as quickly as possible. working with extensions these methods manage webgl extensions: webglrenderingcontext.getsupportedextensions() returns an array of domstring elements with all the supported webgl extensions. webglrenderingcontext.g...
Adding 2D content to a WebGL context - Web APIs
hading language (glsl), that takes information about the vertices that make up a shape and generates the data needed to render the pixels onto the screen: namely, the positions of the pixels and their colors. there are two shader functions run when drawing webgl content: the vertex shader and the fragment shader. you write these in glsl and pass the text of the code into webgl to be compiled for
execution on the gpu. together, a set of vertex and fragment shaders is called a shader program. let's take a quick look at the two types of shader, with the example in mind of drawing a 2d shape into the webgl context. vertex shader each time a shape is rendered, the vertex shader is run for each vertex in the shape. its job is to transform the input vertex from its original coordinate system into the ...
Fundamentals of WebXR - Web APIs
mmon when the user either doesn't have a dedicated xr device, or when the user is viewing the ar or vr app on a phone or other handheld device. simpler and lower-priced xr devices typically use an integrated computer or connect to a smartphone, essentially using the mobile cpu and gpu to run apps, render images, and display them to the user. higher-powered solutions typically offload application
execution and graphics processing to an external device such as a desktop computer, and are either tethered to the computer using a cable or use a wireless network to receive the imagery to display to the user. headsets most immersive vr experiences take place using goggles or a headset of some kind. a vr headset is worn on the head, with a strap that goes behind the head to fasten it in place, and one o...
Inputs and input sources - Web APIs
the event is delivered as an xrinputsourcechangeevent, which includes three properties of interest: session the xrsession for which the input sources have changed. added an array of zero or more xrinputsource objects indicating the input sources that have been newly added to the xr system. removed ...
Rendering and the WebXR frame animation callback - Web APIs
d if tick is an odd value. this way, only every other frame gets rendered. you can similarly render every fourth frame using !(tick % 4), and so forth. matching your animation to the elapsed time the frame callback receives a time parameter for a good reason. this domhighrestimestamp value is a floating-point value indicating the time at which the frame was scheduled for rendering. because the
execution of your callback is not going to happen at precise 1/60th of a second intervals—and, indeed, could happen at other rates if the user's display has a different framer ate—you can't rely on the simple fact that your code is running to assume that it's been 1/60th of a second since the last frame. for that reason, you need to use the timestamp provided to ensure your animation renders at precis...
Web Audio API - Web APIs
e have split up into nine categories of functionality. general audio graph definition general containers and definitions that shape audio graphs in web audio api usage. audiocontext the audiocontext interface represents an audio-processing graph built from audio modules linked together, each represented by an audionode. an audio context controls the creation of the nodes it contains and the
execution of the audio processing, or decoding. you need to create an audiocontext before you do anything else, as everything happens inside a context. audiocontextoptions the audiocontextoptions dictionary is used to provide options when instantiating a new audiocontext. audionode the audionode interface represents an audio-processing module like an audio source (e.g. an html <audio> or <video> elemen...
Web Bluetooth API - Web APIs
low energy peripherals. interfaces bluetooth returns a promise to a bluetoothdevice object with the specified options. bluetoothadvertisingdata provides advertising data about a particular bluetooth device. bluetoothcharacteristicproperties provides properties of a particular bluetoothremotegattcharacteristic. bluetoothdevice represents a bluetooth device inside a particular script
execution environment. bluetoothremotegattcharacteristic represents a gatt characteristic, which is a basic data element that provides further information about a peripheral’s service. bluetoothremotegattdescriptor represents a gatt descriptor, which provides further information about a characteristic’s value. bluetoothremotegattserver represents a gatt server on a remote device. bluetoothremote...
Web Locks API - Web APIs
llows: the lock is requested. work is done while holding the lock in an asynchronous task. the lock is automatically released when the task completes. navigator.locks.request('my_resource', async lock => { // the lock has been acquired. await do_something(); await do_something_else(); // now the lock will be released. }); while a lock is held, requests for the same lock from this
execution context, or from other tabs/workers, will be queued. the first queued request will be granted only when the lock is released. the api provides optional functionality that may be used as needed, including: returning values from the asynchronous task shared and exclusive lock modes conditional acquisition diagnostics to query the state of locks in an origin an escape hatch to protect agains...
Using Web Workers - Web APIs
s have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. there's no access to non-threadsafe components or the dom. and you have to pass specific data in and out of a thread through serialized objects. so you have to work really hard to cause problems in your code. content security policy workers are considered to have their own
execution context, distinct from the document that created them. for this reason they are, in general, not governed by the content security policy of the document (or parent worker) that created them. so for example, suppose a document is served with the following header: content-security-policy: script-src 'self' among other things, this will prevent any scripts it includes from using eval(). however, i...
Web Workers API - Web APIs
the advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the ui) thread to run without being blocked/slowed down. web workers concepts and usage a worker is an object created using a constructor (e.g. worker()) that runs a named javascript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. ...
Window: error event - Web APIs
bubbles no cancelable no interface event or uievent event handler property onerror the event object is a uievent instance if it was generated from a user interface element, or an event instance otherwise. ...
Window.openDialog() - Web APIs
aves the same, except that it can optionally take one or more parameters past windowfeatures, and windowfeatures itself is treated a little differently. the optional parameters, if present, are bundled up in a javascript array object and added to the newly created window as a property named window.arguments. they may be referenced in the javascript of the window at any time, including during the
execution of a load handler. these parameters may be used, then, to pass arguments to and from the dialog window. the call to opendialog() returns immediately. if you want the call to block until the user has closed the dialog, supply modal as a windowfeatures parameter. note that this also means the user won't be able to interact with the opener window until he closes the modal dialog. syntax newwindow...
window.postMessage() - Web APIs
lure to check the origin and possibly source properties enables cross-site scripting attacks. as with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of postmessage to detect when an event handler listening for events sent by postmessage throws an exception. postmessage() schedules the messageevent to be dispatched only after all pending
execution contexts have finished. for example, if postmessage() is invoked in an event handler, that event handler will run to completion, as will any remaining handlers for that same event, before the messageevent is dispatched. the value of the origin property of the dispatched event is not affected by the current value of document.domain in the calling window. for idn host names only, the value of the...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
the queuemicrotask() method, which is exposed on the window or worker interface, queues a microtask to be executed at a safe time prior to control returning to the browser's event loop. the microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the
execution context is returned to the browser's event loop. this lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the
execution context, potentially depending on work you need to complete. you can learn more about how to use microtasks and why you might choose to do so in our microtask guide. the importance of microtasks comes in its ability to perfor...
animation - CSS: Cascading Style Sheets
ion-iteration-count> the number of times the animation is played. the value must be one of those available in animation-iteration-count. <single-animation-direction> the direction in which the animation is played. the value must be one of those available in animation-direction. <single-animation-fill-mode> determines how styles should be applied to the animation's target before and after its
execution. the value must be one of those available in animation-fill-mode. <single-animation-play-state> determines whether the animation is playing or not. the value must be one of those available in animation-play-state. accessibility concerns blinking and flashing animation can be problematic for people with cognitive concerns such as attention deficit hyperactivity disorder (adhd). additionally, ...
Overview of events and handlers - Developer guides
erpetual loop, where waiting for and handling the incidence of new events follows painting. the innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which javascript leverages. (the talk is available from several sources, including this one.) currently, all
execution environments for javascript code use events and event handling. the event design pattern the event system, at its core, is simply a programming design pattern. the pattern starts with an agreement over a kind of event and: the name string used for the event, the type of the data structure used to represent the key properties of that event, and the javascript object which will 'emit' that e...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
d"; preloadlink.as = "script"; document.head.appendchild(preloadlink); this means that the browser will preload the myscript.js file, but not actually use it yet. to use it, you could do this: var preloadedscript = document.createelement("script"); preloadedscript.src = "myscript.js"; document.body.appendchild(preloadedscript); this is useful when you want to preload a script, but then defer
execution until exactly when you need it. other resource preloading mechanisms other preloading features exist, but none are quite as fit for purpose as <link rel="preload">: <link rel="prefetch"> has been supported in browsers for a long time, but it is intended for prefetching resources that will be used in the next navigation/page load (e.g. when you go to the next page). this is fine, but isn't us...
Content Security Policy (CSP) - HTTP
owser should consider to be valid sources of executable scripts. a csp compatible browser will then only execute scripts loaded in source files received from those allowlisted domains, ignoring all other script (including inline scripts and event-handling html attributes). as an ultimate form of protection, sites that want to never allow scripts to be executed can opt to globally disallow script
execution. mitigating packet sniffing attacks in addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used; for example (and ideally, from a security standpoint), a server can specify that all content must be loaded using https. a complete data transmission security strategy includes not only enforcing https for data transfer, but ...
Cross-Origin Resource Policy (CORP) - HTTP
leaked by stripping the response body. history the concept was originally proposed in 2012 (as from-origin), but resurrected in q2 of 2018 and implemented in safari and chromium. in early 2018, two side-channel hardware vulnerabilities known as meltdown and spectre were disclosed. these vulnerabilities allowed sensitive data disclosure due to a race condition which arose as part of speculative
execution functionality, designed to improve performance. in response, chromium shipped cross-origin read blocking, which automatically protects certain resources (of content-type html, json and xml) against cross-origin reads. if the application does not serve a no-sniff directive, chromium will attempt to guess the content-type and apply the protection anyway. cross-origin resource policy is an opt-in ...
CSP: sandbox - HTTP
csp version 1.1 / 2 directive type document directive this directive is not supported in the <meta> element or by the content-security-policy-report-only header field. ...
CSP: worker-src - HTTP
ecurity-policy (csp) worker-src directive specifies valid sources for worker, sharedworker, or serviceworker scripts. csp version 3 directive type fetch directive fallback if this directive is absent, the user agent will first look for the child-src directive, then the script-src directive, then finally for the default-src directive, when governing worker
execution. chrome 59 and higher skips the child-src directive. edge 17 skips the script-src directive (bug). syntax one or more sources can be allowed for the worker-src policy: content-security-policy: worker-src <source>; content-security-policy: worker-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as...
Feature-Policy - HTTP
d to set document.domain. when this policy is disabled, attempting to set document.domain will fail and cause a securityerror domexception to be be thrown. encrypted-media controls whether the current document is allowed to use the encrypted media extensions api (eme). when this policy is disabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a domexception.
execution-while-not-rendered controls whether tasks should execute in frames while they're not being rendered (e.g. if an iframe is hidden or display: none).
execution-while-out-of-viewport controls whether tasks should execute in frames while they're outside of the visible viewport. fullscreen controls whether the current document is allowed to use element.requestfullscreen(). when this policy is ...
An overview of HTTP - HTTP
evelopers to debug their applications. the browser is always the entity initiating the request. it is never the server (though some mechanisms have been added over the years to simulate server-initiated messages). to present a web page, the browser sends an original request to fetch the html document that represents the page. it then parses this file, making additional requests corresponding to
execution scripts, layout information (css) to display, and sub-resources contained within the page (usually images and videos). the web browser then mixes these resources to present to the user a complete document, the web page. scripts executed by the browser can fetch more resources in later phases and the browser updates the web page accordingly. a web page is a hypertext document. this means some par...
CSS Houdini
css painting api developed to improve the extensibility of css — allows developers to write javascript functions that can draw directly into an element's background, border, or content via the paint() css function. css painting api reference css painting api guide worklets an api for running scripts in various stages of the rendering pipeline independent of the main javascript
execution environment. worklets are conceptually similar to web workers, and are called by and extend the rendering engine. worklets reference other topics related topics which may be of interest, since they can be used in tandem with houdini apis in interesting ways. composite scrolling and animation ...
A re-introduction to JavaScript (JS tutorial) - JavaScript
this is very rarely what you want — in fact it's worth specifically labeling deliberate fallthrough with a comment if you really meant it to aid debugging: switch (a) { case 1: // fallthrough case 2: eatit(); break; default: donothing(); } the default clause is optional. you can have expressions in both the switch part and the cases if...
About JavaScript - JavaScript
c/c++. the rhino engine, created primarily by norris boyd (also at netscape) is a javascript implementation written in java. like spidermonkey, rhino is ecma-262 edition 5 compliant. several major runtime optimizations such as tracemonkey (firefox 3.5), jägermonkey (firefox 4) and ionmonkey were added to the spidermonkey javascript engine over time. work is always ongoing to improve javascript
execution performance. besides the above implementations, there are other popular javascript engines such as:- google's v8, which is used in the google chrome browser and recent versions of opera browser. this is also the engine used by node.js. the javascriptcore (squirrelfish/nitro) used in some webkit browsers such as apple safari. carakan in old versions of opera. the chakra engine used in inter...
Closures - JavaScript
xactly the same effect as the previous example of the init() function above. what's different (and interesting) is that the displayname() inner function is returned from the outer function before being executed. at first glance, it might seem unintuitive that this code still works. in some programming languages, the local variables within a function exist for just the duration of that function's
execution. once makefunc() finishes executing, you might expect that the name variable would no longer be accessible. however, because the code still works as expected, this is obviously not the case in javascript. the reason is that functions in javascript form closures. a closure is the combination of a function and the lexical environment within which that function was declared. this environment consis...
Concurrency model and the event loop - JavaScript
new date().getseconds() - s) + " seconds"); }, 500) while (true) { if (new date().getseconds() - s >= 2) { console.log("good, looped for 2 seconds") break; } } zero delays zero delay doesn't actually mean the call back will fire-off after zero milliseconds. calling settimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval. the
execution depends on the number of waiting tasks in the queue. in the example below, the message ''this is just a message'' will be written to the console before the message in the callback gets processed, because the delay is the minimum time required for the runtime to process the request (not a guaranteed time). basically, the settimeout needs to wait for all the code for queued messages to complete ev...
Iterators and generators - JavaScript
eflectively whether a particular object is an iterator. if you need to do this, use iterables. generator functions while custom iterators are a useful tool, their creation requires careful programming due to the need to explicitly maintain their internal state. generator functions provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose
execution is not continuous. generator functions are written using the function* syntax. when called, generator functions do not initially execute their code. instead, they return a special type of iterator, called a generator. when a value is consumed by calling the generator's next method, the generator function executes until it encounters the yield keyword. the function can be called as many times as...
Warning: 08/09 is not a legal ECMA-262 octal constant - JavaScript
the javascript warning "08 (or 09) is not a legal ecma-262 octal constant" occurs when 08 or 09 number literals are used. they can't be interpreted as an octal number. message warning: syntaxerror: 08 is not a legal ecma-262 octal constant. warning: syntaxerror: 09 is not a legal ecma-262 octal constant. error type warning. javascript
execution won't be halted. what went wrong? decimal literals can start with a zero (0) followed by another decimal digit, but if all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. because this is not the case with 08 and 09, javascript warns about it. note that octal literals and octal escape sequences are deprecated and will present an additional deprecation warning. with ecmascript 6 and later, the syntax uses a...
SyntaxError: return not in function - JavaScript
r: 'return' statement outside of function (edge) syntaxerror: return not in function (firefox) syntaxerror: yield not in function (firefox) error type syntaxerror. what went wrong? a return or yield statement is called outside of a function. maybe there are missing curly brackets somewhere? the return and yield statements must be in a function, because they end (or pause and resume) function
execution and specify a value to be returned to the function caller. examples missing curly brackets var cheer = function(score) { if (score === 147) return 'maximum!'; }; if (score > 100) { return 'century!'; } } // syntaxerror: return not in function the curly brackets look correct at a first glance, but this code snippet is missing a { after the first if statement. correct would be:...
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
uppercase is deprecated; use string.prototype.touppercase instead warning: string.trim is deprecated; use string.prototype.trim instead warning: string.trimleft is deprecated; use string.prototype.trimleft instead warning: string.trimright is deprecated; use string.prototype.trimright instead error type warning. javascript
execution won't be halted. what went wrong? the non-standard generic string methods are deprecated and have been removed in firefox 68 and later. string generics provide string instance methods on the string object allowing string methods to be applied to any object. examples deprecated syntax var num = 15; string.replace(num, /5/, '2'); standard syntax var num = 15; string(num).replace(/5/, '2'); ...
ReferenceError: deprecated caller or arguments usage - JavaScript
: 'arguments', 'callee' and 'caller' are restricted function properties and cannot be accessed in this context (edge) warning: referenceerror: deprecated caller usage (firefox) warning: referenceerror: deprecated arguments usage (firefox) typeerror: 'callee' and 'caller' cannot be accessed in strict mode. (safari) error type a strict-mode-only warning that a referenceerror occurred. javascript
execution won't be halted. what went wrong? in strict mode, the function.caller or function.arguments properties are used and shouldn't be. they are deprecated, because they leak the function caller, are non-standard, hard to optimize and potentially a performance-harmful feature. examples deprecated function.caller or arguments.callee.caller function.caller and arguments.callee.caller are deprecated ...
Warning: expression closures are deprecated - JavaScript
what went wrong? the non-standard expression closure syntax (shorthand function syntax) is deprecated and shouldn't be used anymore. this syntax will be removed entirely in bug 1083458 and scripts using it will throw a syntaxerror then. ...
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
icate sourceurl pragmas is deprecated. use //# instead" occurs when there is a deprecated source map syntax in a javascript source. message warning: syntaxerror: using //@ to indicate sourceurl pragmas is deprecated. use //# instead warning: syntaxerror: using //@ to indicate sourcemappingurl pragmas is deprecated. use //# instead error type a warning that a syntaxerror occurred. javascript
execution won't be halted. what went wrong? there is a deprecated source map syntax in a javascript source. javascript sources are often combined and minified to make delivering them from the server more efficient. with source maps, the debugger can map the code being executed to the original source files. the source map specification changed the syntax due to a conflict with ie whenever it was found i...
TypeError: invalid assignment to const "x" - JavaScript
r a constant value. javascript const declarations can't be re-assigned or redeclared. message typeerror: invalid assignment to const "x" (firefox) typeerror: assignment to constant variable. (chrome) typeerror: assignment to const (edge) typeerror: redeclaration of const 'x' (ie) error type typeerror what went wrong? a constant is a value that cannot be altered by the program during normal
execution. it cannot change through re-assignment, and it can't be redeclared. in javascript, constants are declared using the const keyword. examples invalid redeclaration assigning a value to the same constant name in the same block-scope will throw. const columns = 80; // ... columns = 120; // typeerror: invalid assignment to const `columns' fixing the error there are multiple options to fix thi...
SyntaxError: missing = in const declaration - JavaScript
ven a value in the same statement (like const red_flag;). you need to provide one (const red_flag = '#ff0'). message syntaxerror: const must be initalized (edge) syntaxerror: missing = in const declaration (firefox) syntaxerror: missing initializer in const declaration (chrome) error type syntaxerror what went wrong? a constant is a value that cannot be altered by the program during normal
execution. it cannot change through re-assignment, and it can't be redeclared. in javascript, constants are declared using the const keyword. an initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared (which makes sense, given that it can't be changed later). examples missing const initializer unlike var or let, you must specify a value fo...
ReferenceError: "x" is not defined - JavaScript
> tag that loads the library before your code that uses it. examples variable not declared foo.substring(1); // referenceerror: foo is not defined the "foo" variable isn't defined anywhere. it needs to be some string, so that the string.prototype.substring() method will work. var foo = 'bar'; foo.substring(1); // "ar" wrong scope a variable needs to be available in the current context of
execution. variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function function numbers() { var num1 = 2, num2 = 3; return num1 + num2; } console.log(num1); // referenceerror num1 is not defined. however, a function can access all variables and functions defined inside the scope in which it is defi...
Warning: unreachable code after return statement - JavaScript
ctly after. when an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run. why should i have semicolons after return statements? in the case of semicolon-less return statements, it can be unclear whether the developer intended to return the statement on the following line, or to stop
execution and return. the warning indicates that there is ambiguity in the way the return statement is written. warnings will not be shown for semicolon-less returns if these statements follow it: throw break var function examples invalid cases function f() { var x = 3; x += 4; return x; // return exits the function immediately x -= 3; // so this line will never run; it is unreacha...
ReferenceError: assignment to undeclared variable "x" - JavaScript
ng? a value has been assigned to an undeclared variable. in other words, there was an assignment without the var keyword. there are some differences between declared and undeclared variables, which might lead to unexpected results and that's why javascript presents an error in strict mode. three things to note about declared and undeclared variables: declared variables are constrained in the
execution context in which they are declared. undeclared variables are always global. declared variables are created before any code is executed. undeclared variables do not exist until the code assigning to them is executed. declared variables are a non-configurable property of their
execution context (function or global). undeclared variables are configurable (e.g. can be deleted). for more details a...
TypeError: 'x' is not iterable - JavaScript
e functions you call to produce an iterable object. function* generate(a, b) { yield a; yield b; } for (let x of generate) // typeerror: generate is not iterable console.log(x); when they are not called, the function object corresponding to the generator is callable, but not iterable. calling a generator produces an iterable object which will iterate over the values yielded during the
execution of the generator. function* generate(a, b) { yield a; yield b; } for (let x of generate(1,2)) console.log(x); iterating over a custom iterable custom iterables can be created by implementing the symbol.iterator method. you must be certain that your iterator method returns an object which is an iterator, which is to say it must have a next method. const myemptyiterable = { [s...
Array.prototype.reduceRight() - JavaScript
cur; }); console.log(left); // "12345" console.log(right); // "54321" defining composible function the concept of compose function is simple it combines n functions. it’s a flowing right-to-left, calling each function with the output of the last one. /** * function composition is way in which result of one function can * be passed to another and so on. ...
Array.prototype.push() - JavaScript
hat to our advantage. array.prototype.push can work on an object just fine, as this example shows. note that we don't create an array to store a collection of objects. instead, we store the collection on the object itself and use call on array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way javascript allows us to establish the
execution context in any way we want. let obj = { length: 0, addelem: function addelem(elem) { // obj.length is automatically incremented // every time an element is added. [].push.call(this, elem) } } // let's add some empty objects just to illustrate. obj.addelem({}) obj.addelem({}) console.log(obj.length) // → 2 note that although obj is not an array, the metho...
Date.prototype.getTime() - JavaScript
cision will be 100ms or the value of privacy.resistfingerprinting.reducetimerprecision.microseconds, whichever is larger. examples using gettime() for copying dates constructing a date object with the identical time value. // since month is zero based, birthday will be january 10, 1995 var birthday = new date(1994, 12, 10); var copy = new date(); copy.settime(birthday.gettime()); measuring
execution time subtracting two subsequent gettime() calls on newly generated date objects, give the time span between these two calls. this can be used to calculate the executing time of some operations. see also date.now() to prevent instantiating unnecessary date objects. var end, start; start = new date(); for (var i = 0; i < 1000; i++) { math.sqrt(i); } end = new date(); console.log('operation to...
FinalizationRegistry - JavaScript
lementation, even one that does garbage collection, is not required to call cleanup callbacks. when and whether it does so is entirely down to the implementation of the javascript engine. when a registered object is reclaimed, any cleanup callbacks for it may be called then, or some time later, or not at all. it's likely that major implementations will call cleanup callbacks at some point during
execution, but those calls may be substantially after the related object was reclaimed. there are also situations where even implementations that normally call cleanup callbacks are unlikely to call them: when the javascript program shuts down entirely (for instance, closing a tab in a browser). when the finalizationregistry instance itself is no longer reachable by javascript code. exampl...
Function.prototype.bind() - JavaScript
to arguments provided to the bound function when invoking func. return value a copy of the given function with the specified this value, and initial arguments (if provided). description the bind() function creates a new bound function, which is an exotic function object (a term from ecmascript 2015) that wraps the original function object. calling the bound function generally results in the
execution of its wrapped function. a bound function has the following internal properties: [[boundtargetfunction]] the wrapped function object [[boundthis]] the value that is always passed as this value when calling the wrapped function. [[boundarguments]] a list of values whose elements are used as the first arguments to any call to the wrapped function. [[call]] executes code associated with t...
Generator.prototype.throw() - JavaScript
syntax gen.throw(exception) parameters exception the exception to throw. for debugging purposes, it is useful to make it an instanceof error. return value an object with two properties: done (boolean) has the value true if the iterator is past the end of the iterated sequence. in this case value optionally specifies the return value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. value any javascript value returned by the iterator. can be omitted when done is true. ...
JSON.parse() - JavaScript
value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver. then it is called, with the object containing the property being processed as this, and with the property name as a string, and the property value as arguments. if the reviver function returns undefined (or returns no value, for example, if
execution falls off the end of the function), the property is deleted from the object. otherwise, the property is redefined to be the return value. if the reviver only transforms some values and not others, be certain to return all untransformed values as-is, otherwise, they will be deleted from the resulting object. json.parse('{"p": 5}', (key, value) => typeof value === 'number' ? value * 2 // re...
Object.defineProperties() - JavaScript
nction will receive as its only argument the new value being assigned to the property. defaults to undefined. if a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. if a descriptor has both value or writable and get or set keys, an exception is thrown. return value the object that was passed to the function. ...
Promise.prototype.then() - JavaScript
will be triggered asynchronously as demonstrated by the console.logs const resolvedprom = promise.resolve(33); let thenprom = resolvedprom.then(value => { console.log("this gets called after the end of the main stack. the value received and returned is: " + value); return value; }); // instantly logging the value of thenprom console.log(thenprom); // using settimeout we can postpone the
execution of a function to the moment the stack is empty settimeout(() => { console.log(thenprom); }); // logs, in order: // promise {[[promisestatus]]: "pending", [[promisevalue]]: undefined} // "this gets called after the end of the main stack. the value received and returned is: 33" // promise {[[promisestatus]]: "resolved", [[promisevalue]]: 33} description as the then and promise.prototype.cat...
RegExp.prototype.test() - JavaScript
to match the regular expression. returns true if there is a match between the regular expression and the string str. otherwise, false. description use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the string.prototype.search() method (which returns the index of a match, or -1 if not found). to get more information (but with slower
execution), use the exec() method. (this is similar to the string.prototype.match() method.) as with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match. examples using test() simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result. const str = 'hello...
RegExp - JavaScript
e attempting a match in a string. regexp.prototype.multiline whether or not to search in strings across multiple lines. regexp.prototype.source the text of the pattern. regexp.prototype.sticky whether or not the search is sticky. regexp.prototype.unicode whether or not unicode features are enabled. instance methods regexp.prototype.compile() (re-)compiles a regular expression during
execution of a script. regexp.prototype.exec() executes a search for a match in its string parameter. regexp.prototype.test() tests for a match in its string parameter. regexp.prototype.tostring() returns a string representing the specified object. overrides the object.prototype.tostring() method. regexp.prototype[@@match]() performs match to given string and returns match result. regexp.prototype...
String.prototype.search() - JavaScript
return value the index of the first match between the regular expression and the given string, or -1 if no match was found. description when you want to know whether a pattern is found, and also know its index within a string, use search(). (if you only want to know if it exists, use the similar test() method on the regexp prototype, which returns a boolean.) for more information (but slower
execution) use match() (similar to the regular expression exec() method). examples using search() the following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1) let str = "hey jude" let re = /[a-z]/g let redot = /[.]/g console.log(str.search(re)) // returns 4, which is the index of the first capital letter "j" con...
Lexical grammar - JavaScript
u+00a0 no-break space <nbsp> normal space, but no point at which a line may break others other unicode space characters <usp> spaces in unicode on wikipedia line terminators in addition to white space characters, line terminator characters are used to improve the readability of the source text. however, in some cases, line terminators can influence the
execution of javascript code as there are a few places where they are forbidden. line terminators also affect the process of automatic semicolon insertion. line terminators are matched by the \s class in regular expressions. only the following unicode code points are treated as line terminators in ecmascript, other line breaking characters are treated as white space (for example, next line, nel, u+0085 is...
instanceof - JavaScript
e c.prototype is now in o3's prototype chain note that the value of an instanceof test can change based on changes to the prototype property of constructors. it can also be changed by changing an object's prototype using object.setprototypeof. it is also possible using the non-standard __proto__ property. instanceof and multiple context (e.g. frames or windows) different scopes have different
execution environments. this means that they have different built-ins (different global object, different constructors, etc.). this may result in unexpected results. for instance, [] instanceof window.frames[0].array will return false, because array.prototype !== window.frames[0].array and arrays inherit from the former. this may not make sense at first, but for scripts dealing with multiple frames or win...
debugger - JavaScript
ity is available, this statement has no effect. syntax debugger; examples using the debugger statement the following example shows code where a debugger statement has been inserted, to invoke a debugger (if one exists) when the function is called. function potentiallybuggycode() { debugger; // do potentially buggy stuff to examine, step through, etc. } when the debugger is invoked,
execution is paused at the debugger statement. it is like a breakpoint in the script source. specifications specification ecmascript (ecma-262)the definition of 'debugger statement' in that specification. ...
for...of - JavaScript
cument.queryselectorall('article > p'); for (const paragraph of articleparagraphs) { paragraph.classlist.add('read'); } closing iterators in for...of loops, abrupt iteration termination can be caused by break, throw or return. in these cases, the iterator is closed. function* foo(){ yield 1; yield 2; yield 3; }; for (const o of foo()) { console.log(o); break; // closes iterator,
execution continues outside of the loop } console.log('done'); iterating over generators you can also iterate over generators, i.e. functions generating an iterable object: function* fibonacci() { // a generator function let [prev, curr] = [0, 1]; while (true) { [prev, curr] = [curr, prev + curr]; yield curr; } } for (const n of fibonacci()) { console.log(n); // truncate the sequence...
for - JavaScript
are in the same scope the for loop is in. variables declared with let are local to the statement. the result of this expression is discarded. condition an expression to be evaluated before each loop iteration. if this expression evaluates to true, statement is executed. this conditional test is optional. if omitted, the condition always evaluates to true. if the expression evaluates to false,
execution skips to the first expression following the for construct. final-expression an expression to be evaluated at the end of each loop iteration. this occurs before the next evaluation of condition. generally used to update or increment the counter variable. statement a statement that is executed as long as the condition evaluates to true. to execute multiple statements within the loop, use a bloc...
function* - JavaScript
yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. the next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. calling the next() method with an argument will resume the generator function
execution, replacing the yield expression where an
execution was paused with the argument from next(). a return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true). if a value is returned, it will be set as the value property of the object returned by the generator. much like a return statement, an error is thro...
label - JavaScript
label : statement label any javascript identifier that is not a reserved word. statement a javascript statement. break can be used with any labeled statement, and continue can be used with looping labeled statements. description you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its
execution. note that javascript has no goto statement, you can only use labels with break or continue. in strict mode code, you can't use "let" as a label name. it will throw a syntaxerror (let is a reserved identifier). examples using a labeled continue with for loops var i, j; loop1: for (i = 0; i < 3; i++) { //the first for statement is labeled "loop1" loop2: for (j = 0; j < 3; j++) { ...
throw - JavaScript
if no catch block exists among caller functions, the program will terminate. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax throw expression; expression the expression to throw. description use the throw statement to throw an exception. when you throw an exception, expression specifies the value of the exception. ...
var - JavaScript
n [= valuen]]]; varnamen variable name. it can be any legal identifier. valuen optional initial value of the variable. it can be any legal expression. default value is undefined. description var declarations, wherever they occur, are processed before any code is executed. this is called hoisting, and is discussed further below. the scope of a variable declared with var is its current
execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed. 'use strict'; function foo() { var x = 1; function bar() { ...
while - JavaScript
example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax while (condition) statement condition an expression evaluated before each pass through the loop. if this condition evaluates to true, statement is executed. when condition evaluates to false,
execution continues with the statement after the while loop. statement an optional statement that is executed as long as the condition evaluates to true. to execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. note: use the break statement to stop a loop before condition evaluates to true. examples using while the following while loop iterates as ...
with - JavaScript
with (expression) statement expression adds the given expression to the scope chain used when evaluating the statement. the parentheses around the expression are required. statement any statement. to execute multiple statements, use a block statement ({ ... }) to group those statements. description javascript looks up an unqualified name by searching a scope chain associated with the
execution context of the script or function containing that unqualified name. the 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. if an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property. otherwise a referenceerror is thrown. using with is ...
Statements and declarations - JavaScript
tements and declarations by category for an alphabetical listing see the sidebar on the left. control flow block a block statement is used to group zero or more statements. the block is delimited by a pair of curly brackets. break terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement. continue terminates
execution of the statements in the current iteration of the current or labeled loop, and continues
execution of the loop with the next iteration. empty an empty statement is used to provide no statement, although the javascript syntax would expect one. if...else executes a statement if a specified condition is true. if the condition is false, another statement can be executed. switch evaluates an exp...
Populating the page: how browsers work - Web Performance
pt.js" async></script> <img src="myimage.jpg" alt="image description"/> <script src="anotherscript.js" async></script> in this example, while the main thread is parsing the html and css, the preload scanner will find the scripts and image, and start downloading them as well. to ensure the script doesn't block the process, add the async attribute, or the defer attribute if javascript parsing and
execution order is not important. waiting to obtain css doesn't block html parsing or downloading, but it does block javascript, because javascript is often used to query css properties’ impact on elements. building the cssom the second step in the critical rendering path is processing css and building the cssom tree. the css object model is similar to the dom. the dom and cssom are both trees. they a...
Recommended Web Performance Timings: How long is too long? - Web Performance
load goals for subsequent page loads, leveraging service workers and caching. there are different suggested times for initially loading the page versus loading additional assets, responding to user interaction, and ensuring smooth animations: idling goal browsers are single threaded (though background threads are supported for web workers). this means that user interaction, painting, and script
execution are all on the same thread. if the thread is busy doing complex javascript
execution, the main thread will not be available to react to user input, such as pressing a button. for this reason, script
execution should be limited in scope, divided into chunks of code that can be executed in 50ms or less. this makes the thread available for user interactions. animation goal for scrolling and other ...
<xsl:message> - XSLT: Extensible Stylesheet Language Transformations
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:message> element outputs a message (to the javascript console in ns) and optionally terminates
execution of the stylesheet. it can be useful for debugging. syntax <xsl:message terminate="yes" | "no" > template </xsl:message> required attributes none. optional attributes terminate set to "yes", indicates that
execution should be terminated. the default value is "no", in which case the message is output and
execution continues. type instruction, appears within a template. defined xslt, section 13. gecko support supported. ...
Index - XSLT: Extensible Stylesheet Language Transformations
as the contents of the including stylesheet. 36 <xsl:key> element, key, reference, xslt the <xsl:key> element declares a named key which can be used elsewhere in the stylesheet with the key( ) function. 37 <xsl:message> element, reference, xslt, message the <xsl:message> element outputs a message (to the javascript console in ns) and optionally terminates
execution of the stylesheet. it can be useful for debugging. 38 <xsl:namespace-alias> element, reference, xslt, namespace-alias the <xsl:namespace-alias> element is a rarely used device that maps a namespace in the stylesheet to a different namespace in the output tree. the most common use for this element is in generating a stylesheet from another stylesheet. to prevent a normally xsl...
An Overview - XSLT: Extensible Stylesheet Language Transformations
the browser window. xslt is a high-level declarative language. in essence, an xslt stylesheet is a set of rules, called templates, which declare that any node that matches this specific pattern should be manipulated in this specific way and end up in this specific position in the result tree. the particulars of how this is to be accomplished are left up to the processor. because the order of
execution of the stylesheet cannot be guaranteed, xslt does not support any functionality that produces side-effects. in this it is like lisp or scheme. locations on the tree are specified using xpath, another w3c recommendation. transformations depend on the processor's being able to pinpoint individual nodes on the tree. to facilitate this, the w3c decided to use a separate language, xpath, which also ...
WebAssembly Concepts - WebAssembly
speed across different platforms by taking advantage of common hardware capabilities. be readable and debuggable — webassembly is a low-level assembly language, but it does have a human-readable text format (the specification for which is still being finalized) that allows code to be written, viewed, and debugged by hand. keep secure — webassembly is specified to be run in a safe, sandboxed
execution environment. like other web code, it will enforce the browser's same-origin and permissions policies. don't break the web — webassembly is designed so that it plays nicely with other web technologies and maintains backwards compatibility. note: webassembly will also have uses outside web and javascript environments (see non-web embeddings). how does webassembly fit into the web platform? ...
Understanding WebAssembly text format - WebAssembly
c (param $p1 i32) (param $p2 f32) (local $loc f64) …) and then could write local.get $p1 instead of local.get 0, etc. (note that when this text gets converted to binary, though, the binary will contain only the integer.) stack machines before we can write a function body, we have to talk about one more thing: stack machines. although the browser compiles it to something more efficient, wasm
execution is defined in terms of a stack machine where the basic idea is that every type of instruction pushes and/or pops a certain number of i32/i64/f32/f64 values to/from a stack. for example, local.get is defined to push the value of the local it read onto the stack, and i32.add pops two i32 values (it implicitly grabs the previous two values pushed onto the stack), computes their sum (modulo 2^32) an...