HTML Standard
10
Web workers
10.1
Introduction
10.1.1
Scope
10.1.2
Examples
10.1.2.1
A background number-crunching worker
10.1.2.2
Using a JavaScript module as a worker
10.1.2.3
Shared workers introduction
10.1.2.4
Shared state using a shared worker
10.1.2.5
Delegation
10.1.2.6
Providing libraries
10.1.3
Tutorials
10.1.3.1
Creating a dedicated worker
10.1.3.2
Communicating with a dedicated worker
10.1.3.3
Shared workers
10.2
Infrastructure
10.2.1
The global scope
10.2.1.1
The
WorkerGlobalScope
common interface
10.2.1.2
Dedicated workers and the
DedicatedWorkerGlobalScope
interface
10.2.1.3
Shared workers and the
SharedWorkerGlobalScope
interface
10.2.2
The event loop
10.2.3
The worker's lifetime
10.2.4
Processing model
10.2.5
Runtime script errors
10.2.6
Creating workers
10.2.6.1
The
AbstractWorker
mixin
10.2.6.2
Script settings for workers
10.2.6.3
Dedicated workers and the
Worker
interface
10.2.6.4
Shared workers and the
SharedWorker
interface
10.2.7
Concurrent hardware capabilities
10.3
APIs available to workers
10.3.1
Importing scripts and libraries
10.3.2
The
WorkerNavigator
interface
10.3.3
The
WorkerLocation
interface
10
Web workers
Web_Workers_API
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
2+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
Web_Workers_API/Using_web_workers
10.1
Introduction
10.1.1
Scope
This section is non-normative.
This specification defines an API for running scripts in the background independently of any
user interface scripts.
This allows for long-running scripts that are not interrupted by scripts that respond to clicks
or other user interactions, and allows long tasks to be executed without yielding to keep the page
responsive.
Workers (as these background scripts are called herein) are relatively heavy-weight, and are
not intended to be used in large numbers. For example, it would be inappropriate to launch one
worker for each pixel of a four megapixel image. The examples below show some appropriate uses of
workers.
Generally, workers are expected to be long-lived, have a high start-up performance cost, and a
high per-instance memory cost.
10.1.2
Examples
This section is non-normative.
There are a variety of uses that workers can be put to. The following subsections show various
examples of this use.
10.1.2.1
A background number-crunching worker
This section is non-normative.
The simplest use of workers is for performing a computationally
expensive task without interrupting the user interface.
In this example, the main document spawns a worker to (naïvely) compute prime numbers, and
progressively displays the most recently found prime number.
The main page is as follows:

html
lang
"en"
head
meta
charset
"utf-8"
title
Worker example: One-core computation
title
head
body
The highest prime number discovered so far is:
output
id
"result"
>output
>script
var
worker
new
Worker
'worker.js'
);
worker
onmessage
function
event
document
getElementById
'result'
).
textContent
event
data
};
script
body
html
The
Worker()
constructor call creates a worker and returns a
Worker
object representing that worker, which is used to communicate with the worker.
That object's
onmessage
event handler
allows the code to receive messages from the worker.
The worker itself is as follows:
var
while
true
+=
for
var
<=
Math
sqrt
);
+=
if
==
continue
// found a prime!
postMessage
);
The bulk of this code is simply an unoptimized search for a prime number. The
postMessage()
method is used to send a
message back to the page when a prime is found.
View this example online
10.1.2.2
Using a JavaScript module as a worker
This section is non-normative.
All of our examples so far show workers that run
classic
scripts
. Workers can instead be instantiated using
module
scripts
, which have the usual benefits: the ability to use the JavaScript
import
statement to import other modules; strict mode by default; and
top-level declarations not polluting the worker's global scope.
As the
import
statement is available, the
importScripts()
method will automatically fail
inside module workers.
In this example, the main document uses a worker to do off-main-thread image manipulation.
It imports the filters used from another module.
The main page is as follows:

html
lang
"en"
meta
charset
"utf-8"
title
Worker example: image decoding
title
label
Type an image URL to decode
input
type
"url"
id
"image-url"
list
"image-list"
datalist
id
"image-list"
option
value
"https://html.spec.whatwg.org/images/drawImage.png"
option
value
"https://html.spec.whatwg.org/images/robots.jpeg"
option
value
"https://html.spec.whatwg.org/images/arcTo2.png"
datalist
label
label
Choose a filter to apply
select
id
"filter"
option
value
"none"
none
option
option
value
"grayscale"
grayscale
option
option
value
"brighten"
brighten by 20%
option
select
label
div
id
"output"
>div
script
type
"module"
const
worker
new
Worker
"worker.js"
type
"module"
});
worker
onmessage
receiveFromWorker
const
url
document
querySelector
"#image-url"
);
const
filter
document
querySelector
"#filter"
);
const
output
document
querySelector
"#output"
);
url
oninput
updateImage
filter
oninput
sendToWorker
let
imageData
context
function
updateImage
()
const
img
new
Image
();
img
src
url
value
img
onload
()
=>
const
canvas
document
createElement
"canvas"
);
canvas
width
img
width
canvas
height
img
height
context
canvas
getContext
"2d"
);
context
drawImage
img
);
imageData
context
getImageData
canvas
width
canvas
height
);
sendToWorker
();
output
replaceChildren
canvas
);
};
function
sendToWorker
()
worker
postMessage
({
imageData
filter
filter
value
});
function
receiveFromWorker
context
putImageData
data
);
script
The worker file is then:
import
as
filters
from
"./filters.js"
self
onmessage
=>
const
imageData
filter
data
filters
filter
](
imageData
);
self
postMessage
imageData
imageData
data
buffer
]);
};
Which imports the file
filters.js
export
function
none
()
{}
export
function
grayscale
({
data
})
for
let
length
+=
const
],
],
]];
// CIE luminance for the RGB
// The human eye is bad at seeing red and blue, so we de-emphasize them.
0.2126
0.7152
0.0722
};
export
function
brighten
({
data
})
for
let
length
++
*=
1.2
};
View this example online
10.1.2.3
Shared workers introduction
SharedWorker
Support in all current engines.
Firefox
29+
Safari
16+
Chrome
5+
Opera
10.6+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
33+
Safari iOS
16+
Chrome Android
No
WebView Android
Samsung Internet
4.0–5.0
Opera Android
11–14
This section is non-normative.
This section introduces shared workers using a Hello World example. Shared workers use slightly
different APIs, since each worker can have multiple connections.
This first example shows how you connect to a worker and how a worker can send a message back
to the page when it connects to it. Received messages are displayed in a log.
Here is the HTML page:

html
lang
"en"
meta
charset
"utf-8"
title
Shared workers: demo 1
title
pre
id
"log"
Log:
pre
script
var
worker
new
SharedWorker
'test.js'
);
var
log
document
getElementById
'log'
);
worker
port
onmessage
function
// note: not worker.onmessage!
log
textContent
+=
'\n'
data
script
Here is the JavaScript worker:
onconnect
function
var
port
ports
];
port
postMessage
'Hello World!'
);
View this example online
This second example extends the first one by changing two things: first, messages are received
using
addEventListener()
instead of an
event handler IDL attribute
, and second, a message is sent
to
the
worker, causing the worker to send another message in return. Received messages are again
displayed in a log.
Here is the HTML page:

html
lang
"en"
meta
charset
"utf-8"
title
Shared workers: demo 2
title
pre
id
"log"
Log:
pre
script
var
worker
new
SharedWorker
'test.js'
);
var
log
document
getElementById
'log'
);
worker
port
addEventListener
'message'
function
log
textContent
+=
'\n'
data
},
false
);
worker
port
start
();
// note: need this when using addEventListener
worker
port
postMessage
'ping'
);
script
Here is the JavaScript worker:
onconnect
function
var
port
ports
];
port
postMessage
'Hello World!'
);
port
onmessage
function
port
postMessage
'pong'
);
// not e.ports[0].postMessage!
// e.target.postMessage('pong'); would work also
View this example online
Finally, the example is extended to show how two pages can connect to the same worker; in this
case, the second page is merely in an
iframe
on the first page, but the same
principle would apply to an entirely separate page in a separate
top-level
traversable
Here is the outer HTML page:

html
lang
"en"
meta
charset
"utf-8"
title
Shared workers: demo 3
title
pre
id
"log"
Log:
pre
script
var
worker
new
SharedWorker
'test.js'
);
var
log
document
getElementById
'log'
);
worker
port
addEventListener
'message'
function
log
textContent
+=
'\n'
data
},
false
);
worker
port
start
();
worker
port
postMessage
'ping'
);
script
iframe
src
"inner.html"
>iframe
Here is the inner HTML page:

html
lang
"en"
meta
charset
"utf-8"
title
Shared workers: demo 3 inner frame
title
pre
id
log
Inner log:
pre
script
var
worker
new
SharedWorker
'test.js'
);
var
log
document
getElementById
'log'
);
worker
port
onmessage
function
log
textContent
+=
'\n'
data
script
Here is the JavaScript worker:
var
count
onconnect
function
count
+=
var
port
ports
];
port
postMessage
'Hello World! You are connection #'
count
);
port
onmessage
function
port
postMessage
'pong'
);
View this example online
10.1.2.4
Shared state using a shared worker
This section is non-normative.
In this example, multiple windows (viewers) can be opened that are all viewing the same map.
All the windows share the same map information, with a single worker coordinating all the viewers.
Each viewer can move around independently, but if they set any data on the map, all the viewers
are updated.
The main page isn't interesting, it merely provides a way to open the viewers:

html
lang
"en"
head
meta
charset
"utf-8"
title
Workers example: Multiviewer
title
script
function
openViewer
()
window
open
'viewer.html'
);
script
head
body
><
button
type
button
onclick
"openViewer()"
Open a new
viewer
button
>Each viewer opens in a new window. You can have as many viewers
as you like, they all view the same data.
body
html
The viewer is more involved:

html
lang
"en"
head
meta
charset
"utf-8"
title
Workers example: Multiviewer viewer
title
script
var
worker
new
SharedWorker
'worker.js'
'core'
);
// CONFIGURATION
function
configure
event
if
event
data
substr
!=
'cfg '
return
var
name
event
data
substr
).
split
' '
)[
];
// update display to mention our name is name
document
getElementsByTagName
'h1'
)[
].
textContent
+=
' '
name
// no longer need this listener
worker
port
removeEventListener
'message'
configure
false
);
worker
port
addEventListener
'message'
configure
false
);
// MAP
function
paintMap
event
if
event
data
substr
!=
'map '
return
var
data
event
data
substr
).
split
','
);
// display tiles data[0] .. data[8]
var
canvas
document
getElementById
'map'
);
var
context
canvas
getContext
'2d'
);
for
var
+=
for
var
+=
var
tile
data
];
if
tile
==
'0'
context
fillStyle
'green'
else
context
fillStyle
'maroon'
context
fillRect
50
50
50
50
);
worker
port
addEventListener
'message'
paintMap
false
);
// PUBLIC CHAT
function
updatePublicChat
event
if
event
data
substr
!=
'txt '
return
var
name
event
data
substr
).
split
' '
)[
];
var
message
event
data
substr
name
length
);
// display " message" in public chat
var
public
document
getElementById
'public'
);
var
document
createElement
'p'
);
var
document
createElement
'button'
);
textContent
'<'
name
'> '
onclick
function
()
worker
port
postMessage
'msg '
name
);
};
appendChild
);
var
document
createElement
'span'
);
textContent
message
appendChild
);
public
appendChild
);
worker
port
addEventListener
'message'
updatePublicChat
false
);
// PRIVATE CHAT
function
startPrivateChat
event
if
event
data
substr
!=
'msg '
return
var
name
event
data
substr
).
split
' '
)[
];
var
port
event
ports
];
// display a private chat UI
var
ul
document
getElementById
'private'
);
var
li
document
createElement
'li'
);
var
h3
document
createElement
'h3'
);
h3
textContent
'Private chat with '
name
li
appendChild
h3
);
var
div
document
createElement
'div'
);
var
addMessage
function
name
message
var
document
createElement
'p'
);
var
document
createElement
'strong'
);
textContent
'<'
name
'> '
appendChild
);
var
document
createElement
'span'
);
textContent
message
appendChild
);
div
appendChild
);
};
port
onmessage
function
event
addMessage
name
event
data
);
};
li
appendChild
div
);
var
form
document
createElement
'form'
);
var
document
createElement
'p'
);
var
input
document
createElement
'input'
);
input
size
50
appendChild
input
);
appendChild
document
createTextNode
' '
));
var
button
document
createElement
'button'
);
button
textContent
'Post'
appendChild
button
);
form
onsubmit
function
()
port
postMessage
input
value
);
addMessage
'me'
input
value
);
input
value
''
return
false
};
form
appendChild
);
li
appendChild
form
);
ul
appendChild
li
);
worker
port
addEventListener
'message'
startPrivateChat
false
);
worker
port
start
();
script
head
body
h1
Viewer
h1
h2
Map
h2
><
canvas
id
"map"
height
150
width
150
>canvas
>button
type
button
onclick
"worker.port.postMessage('mov left')"
Left
button
button
type
button
onclick
"worker.port.postMessage('mov up')"
Up
button
button
type
button
onclick
"worker.port.postMessage('mov down')"
Down
button
button
type
button
onclick
"worker.port.postMessage('mov right')"
Right
button
button
type
button
onclick
"worker.port.postMessage('set 0')"
Set 0
button
button
type
button
onclick
"worker.port.postMessage('set 1')"
Set 1
button
h2
Public Chat
h2
div
id
"public"
>div
form
onsubmit
"worker.port.postMessage('txt ' + message.value); message.value = ''; return false;"
input
type
"text"
name
"message"
size
"50"
button
Post
button
form
h2
Private Chat
h2
ul
id
"private"
>ul
body
html
There are several key things worth noting about the way the viewer is written.
Multiple listeners
. Instead of a single message processing function, the code
here attaches multiple event listeners, each one performing a quick check to see if it is relevant
for the message. In this example it doesn't make much difference, but if multiple authors wanted
to collaborate using a single port to communicate with a worker, it would allow for independent
code instead of changes having to all be made to a single event handling function.
Registering event listeners in this way also allows you to unregister specific listeners when
you are done with them, as is done with the
configure()
method in this
example.
Finally, the worker:
var
nextName
function
getNextName
()
// this could use more friendly names
// but for now just return a number
return
nextName
++
var
map
],
],
],
],
],
],
],
];
function
wrapX
if
return
wrapX
map
].
length
);
if
>=
map
].
length
return
wrapX
map
].
length
);
return
function
wrapY
if
return
wrapY
map
length
);
if
>=
map
].
length
return
wrapY
map
length
);
return
function
wrap
val
min
max
if
val
min
return
val
max
min
if
val
max
return
val
max
min
return
val
function
sendMapData
viewer
var
data
''
for
var
viewer
<=
viewer
+=
for
var
viewer
<=
viewer
+=
if
data
!=
''
data
+=
','
data
+=
map
wrap
map
].
length
)][
wrap
map
length
)];
viewer
port
postMessage
'map '
data
);
var
viewers
{};
onconnect
function
event
var
name
getNextName
();
event
ports
].
_data
port
event
ports
],
name
name
};
viewers
name
event
ports
].
_data
event
ports
].
postMessage
'cfg '
name
);
event
ports
].
onmessage
getMessage
sendMapData
event
ports
].
_data
);
};
function
getMessage
event
switch
event
data
substr
))
case
'mov '
var
direction
event
data
substr
);
var
dx
var
dy
switch
direction
case
'up'
dy
break
case
'down'
dy
break
case
'left'
dx
break
case
'right'
dx
break
event
target
_data
wrapX
event
target
_data
dx
);
event
target
_data
wrapY
event
target
_data
dy
);
sendMapData
event
target
_data
);
break
case
'set '
var
value
event
data
substr
);
map
event
target
_data
][
event
target
_data
value
for
var
viewer
in
viewers
sendMapData
viewers
viewer
]);
break
case
'txt '
var
name
event
target
_data
name
var
message
event
data
substr
);
for
var
viewer
in
viewers
viewers
viewer
].
port
postMessage
'txt '
name
' '
message
);
break
case
'msg '
var
party1
event
target
_data
var
party2
viewers
event
data
substr
).
split
' '
)[
]];
if
party2
var
channel
new
MessageChannel
();
party1
port
postMessage
'msg '
party2
name
channel
port1
]);
party2
port
postMessage
'msg '
party1
name
channel
port2
]);
break
Connecting to multiple pages
. The script uses the
onconnect
event listener to listen for
multiple connections.
Direct channels
. When the worker receives a "msg" message from one viewer
naming another viewer, it sets up a direct connection between the two, so that the two viewers can
communicate directly without the worker having to proxy all the messages.
View this example online
10.1.2.5
Delegation
This section is non-normative.
With multicore CPUs becoming prevalent, one way to obtain better performance is to split
computationally expensive tasks amongst multiple workers. In this example, a computationally
expensive task that is to be performed for every number from 1 to 10,000,000 is farmed out to ten
subworkers.
The main page is as follows, it just reports the result:

html
lang
"en"
head
meta
charset
"utf-8"
title
Worker example: Multicore computation
title
head
body
Result:
output
id
"result"
>output
>script
var
worker
new
Worker
'worker.js'
);
worker
onmessage
function
event
document
getElementById
'result'
).
textContent
event
data
};
script
body
html
The worker itself is as follows:
// settings
var
num_workers
10
var
items_per_worker
1000000
// start the workers
var
result
var
pending_workers
num_workers
for
var
num_workers
+=
var
worker
new
Worker
'core.js'
);
worker
postMessage
items_per_worker
);
worker
postMessage
((
items_per_worker
);
worker
onmessage
storeResult
// handle the results
function
storeResult
event
result
+=
event
data
pending_workers
-=
if
pending_workers
<=
postMessage
result
);
// finished!
It consists of a loop to start the subworkers, and then a handler
that waits for all the subworkers to respond.
The subworkers are implemented as follows:
var
start
onmessage
getStart
function
getStart
event
start
event
data
onmessage
getEnd
var
end
function
getEnd
event
end
event
data
onmessage
null
work
();
function
work
()
var
result
for
var
start
end
+=
// perform some complex calculation here
result
+=
postMessage
result
);
close
();
They receive two numbers in two events, perform the computation for the range of numbers thus
specified, and then report the result back to the parent.
View this example online
10.1.2.6
Providing libraries
This section is non-normative.
Suppose that a cryptography library is made available that provides three tasks:
Generate a public/private key pair
Takes a port, on which it will send two messages, first the public key and then the private
key.
Given a plaintext and a public key, return the corresponding ciphertext
Takes a port, to which any number of messages can be sent, the first giving the public key,
and the remainder giving the plaintext, each of which is encrypted and then sent on that same
channel as the ciphertext. The user can close the port when it is done encrypting content.
Given a ciphertext and a private key, return the corresponding plaintext
Takes a port, to which any number of messages can be sent, the first giving the private key,
and the remainder giving the ciphertext, each of which is decrypted and then sent on that same
channel as the plaintext. The user can close the port when it is done decrypting content.
The library itself is as follows:
function
handleMessage
if
data
==
"genkeys"
genkeys
ports
]);
else
if
data
==
"encrypt"
encrypt
ports
]);
else
if
data
==
"decrypt"
decrypt
ports
]);
function
genkeys
var
keys
_generateKeyPair
();
postMessage
keys
]);
postMessage
keys
]);
function
encrypt
var
key
state
onmessage
function
if
state
==
key
data
state
else
postMessage
_encrypt
key
data
));
};
function
decrypt
var
key
state
onmessage
function
if
state
==
key
data
state
else
postMessage
_decrypt
key
data
));
};
// support being used as a shared worker as well as a dedicated worker
if
'onmessage'
in
this
// dedicated worker
onmessage
handleMessage
else
// shared worker
onconnect
function
port
onmessage
handleMessage
// the "crypto" functions:
function
_generateKeyPair
()
return
Math
random
(),
Math
random
()];
function
_encrypt
return
'encrypted-'
' '
function
_decrypt
return
substr
indexOf
' '
);
Note that the crypto functions here are just stubs and don't do real cryptography.
This library could be used as follows:

html
lang
"en"
head
meta
charset
"utf-8"
title
Worker example: Crypto library
title
script
const
cryptoLib
new
Worker
'libcrypto-v1.js'
);
// or could use 'libcrypto-v2.js'
function
startConversation
source
message
const
messageChannel
new
MessageChannel
();
source
postMessage
message
messageChannel
port2
]);
return
messageChannel
port1
function
getKeys
()
let
state
startConversation
cryptoLib
"genkeys"
).
onmessage
function
if
state
===
document
getElementById
'public'
).
value
data
else
if
state
===
document
getElementById
'private'
).
value
data
state
+=
};
function
enc
()
const
port
startConversation
cryptoLib
"encrypt"
);
port
postMessage
document
getElementById
'public'
).
value
);
port
postMessage
document
getElementById
'input'
).
value
);
port
onmessage
function
document
getElementById
'input'
).
value
data
port
close
();
};
function
dec
()
const
port
startConversation
cryptoLib
"decrypt"
);
port
postMessage
document
getElementById
'private'
).
value
);
port
postMessage
document
getElementById
'input'
).
value
);
port
onmessage
function
document
getElementById
'input'
).
value
data
port
close
();
};
script
style
textarea
display
block
style
head
body
onload
"getKeys()"
fieldset
legend
Keys
legend
><
label
Public Key:
textarea
id
"public"
>textarea
>label
>><
label
Private Key:
textarea
id
"private"
>textarea
>label
>fieldset
><
label
Input:
textarea
id
"input"
>textarea
>label
>><
button
onclick
"enc()"
Encrypt
button
button
onclick
"dec()"
Decrypt
button
>body
html
A later version of the API, though, might want to offload all the crypto work onto subworkers.
This could be done as follows:
function
handleMessage
if
data
==
"genkeys"
genkeys
ports
]);
else
if
data
==
"encrypt"
encrypt
ports
]);
else
if
data
==
"decrypt"
decrypt
ports
]);
function
genkeys
var
generator
new
Worker
'libcrypto-v2-generator.js'
);
generator
postMessage
''
]);
function
encrypt
onmessage
function
var
key
data
var
encryptor
new
Worker
'libcrypto-v2-encryptor.js'
);
encryptor
postMessage
key
]);
};
function
encrypt
onmessage
function
var
key
data
var
decryptor
new
Worker
'libcrypto-v2-decryptor.js'
);
decryptor
postMessage
key
]);
};
// support being used as a shared worker as well as a dedicated worker
if
'onmessage'
in
this
// dedicated worker
onmessage
handleMessage
else
// shared worker
onconnect
function
ports
].
onmessage
handleMessage
};
The little subworkers would then be as follows.
For generating key pairs:
onmessage
function
var
_generateKeyPair
();
ports
].
postMessage
]);
ports
].
postMessage
]);
close
();
function
_generateKeyPair
()
return
Math
random
(),
Math
random
()];
For encrypting:
onmessage
function
var
key
data
ports
].
onmessage
function
var
data
postMessage
_encrypt
key
));
function
_encrypt
return
'encrypted-'
' '
For decrypting:
onmessage
function
var
key
data
ports
].
onmessage
function
var
data
postMessage
_decrypt
key
));
function
_decrypt
return
substr
indexOf
' '
);
Notice how the users of the API don't have to even know that this is happening — the API
hasn't changed; the library can delegate to subworkers without changing its API, even though it is
accepting data using message channels.
View this example online
10.1.3
Tutorials
10.1.3.1
Creating a dedicated worker
This section is non-normative.
Creating a worker requires a URL to a JavaScript file. The
Worker()
constructor is invoked with the URL to that file as its only
argument; a worker is then created and returned:
var
worker
new
Worker
'helper.js'
);
If you want your worker script to be interpreted as a
module script
instead of
the default
classic script
, you need to use a slightly different signature:
var
worker
new
Worker
'helper.mjs'
type
"module"
});
10.1.3.2
Communicating with a dedicated worker
This section is non-normative.
Dedicated workers use
MessagePort
objects behind the scenes, and thus support all
the same features, such as sending structured data, transferring binary data, and transferring
other ports.
To receive messages from a dedicated worker, use the
onmessage
event handler IDL attribute
on the
Worker
object:
worker
onmessage
function
event
...
};
You can also use the
addEventListener()
method.
The implicit
MessagePort
used by dedicated workers has its
port
message queue
implicitly enabled when it is created, so there is no equivalent to the
MessagePort
interface's
start()
method on
the
Worker
interface.
To
send
data to a worker, use the
postMessage()
method. Structured data can be sent over this
communication channel. To send
ArrayBuffer
objects
efficiently (by transferring them rather than cloning them), list them in an array in the second
argument.
worker
postMessage
({
operation
'find-edges'
input
buffer
// an ArrayBuffer object
threshold
0.6
},
buffer
]);
To receive a message inside the worker, the
onmessage
event handler IDL attribute
is used.
onmessage
function
event
...
};
You can again also use the
addEventListener()
method.
In either case, the data is provided in the event object's
data
attribute.
To send messages back, you again use
postMessage()
. It supports the
structured data in the same manner.
postMessage
event
data
input
event
data
input
]);
// transfer the buffer back
10.1.3.3
Shared workers
SharedWorker
Support in all current engines.
Firefox
29+
Safari
16+
Chrome
5+
Opera
10.6+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
33+
Safari iOS
16+
Chrome Android
No
WebView Android
Samsung Internet
4.0–5.0
Opera Android
11–14
This section is non-normative.
Shared workers are identified by the URL of the script used to create it, optionally with an
explicit name. The name allows multiple instances of a particular shared worker to be started.
Shared workers are scoped by
origin
. Two different sites using the same names will
not collide. However, if a page tries to use the same shared worker name as another page on the
same site, but with a different script URL, it will fail.
Creating shared workers is done using the
SharedWorker()
constructor. This constructor takes the URL to the script to use for its first argument, and the
name of the worker, if any, as the second argument.
var
worker
new
SharedWorker
'service.js'
);
Communicating with shared workers is done with explicit
MessagePort
objects. The
object returned by the
SharedWorker()
constructor holds a
reference to the port on its
port
attribute.
worker
port
onmessage
function
event
...
};
worker
port
postMessage
'some message'
);
worker
port
postMessage
({
foo
'structured'
bar
'data'
'also'
'possible'
]});
Inside the shared worker, new clients of the worker are announced using the
connect
event. The port for the new client is
given by the event object's
source
attribute.
onconnect
function
event
var
newPort
event
source
// set up a listener
newPort
onmessage
function
event
...
};
// send a message back to the port
newPort
postMessage
'ready!'
);
// can also send structured data, of course
};
10.2
Infrastructure
This standard defines two kinds of workers: dedicated workers, and shared workers. Dedicated
workers, once created, are linked to their creator, but message ports can be used to communicate
from a dedicated worker to multiple other browsing contexts or workers. Shared workers, on the
other hand, are named, and once created any script running in the same
origin
can
obtain a reference to that worker and communicate with it.
Service Workers
defines a
third kind.
[SW]
10.2.1
The global scope
The global scope is the "inside" of a worker.
10.2.1.1
The
WorkerGlobalScope
common interface
WorkerGlobalScope
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
Exposed
Worker
interface
WorkerGlobalScope
EventTarget
readonly
attribute
WorkerGlobalScope
self
readonly
attribute
WorkerLocation
location
readonly
attribute
WorkerNavigator
navigator
undefined
importScripts
((
TrustedScriptURL
or
USVString
)...
urls
);
attribute
OnErrorEventHandler
onerror
attribute
EventHandler
onlanguagechange
attribute
EventHandler
onoffline
attribute
EventHandler
ononline
attribute
EventHandler
onrejectionhandled
attribute
EventHandler
onunhandledrejection
};
WorkerGlobalScope
serves as the base class for specific types of worker global
scope objects, including
DedicatedWorkerGlobalScope
SharedWorkerGlobalScope
, and
ServiceWorkerGlobalScope
WorkerGlobalScope
object has an associated
owner set
(a
set
of
Document
and
WorkerGlobalScope
objects). It is
initially empty and populated when the worker is created or obtained.
It is a
set
, instead of a single owner, to accommodate
SharedWorkerGlobalScope
objects.
WorkerGlobalScope
object has an associated
type
("
classic
" or "
module
"). It is set during creation.
WorkerGlobalScope
object has an associated
url
(null or a
URL
). It is initially
null.
WorkerGlobalScope
object has an associated
name
(a string). It is set during creation.
The
name
can have different
semantics for each subclass of
WorkerGlobalScope
. For
DedicatedWorkerGlobalScope
instances, it is simply a developer-supplied name, useful
mostly for debugging purposes. For
SharedWorkerGlobalScope
instances, it allows
obtaining a reference to a common shared worker via the
SharedWorker()
constructor. For
ServiceWorkerGlobalScope
objects, it doesn't make sense (and as such isn't exposed
through the JavaScript API at all).
WorkerGlobalScope
object has an associated
policy container
(a
policy
container
). It is initially a new
policy container
WorkerGlobalScope
object has an associated
embedder policy
(an
embedder
policy
).
WorkerGlobalScope
object has an associated
module map
. It is a
module map
initially empty.
WorkerGlobalScope
object has an associated
cross-origin isolated
capability
boolean. It is initially false.
workerGlobal
self
WorkerGlobalScope/self
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
11.5+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
34+
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
Returns
workerGlobal
workerGlobal
location
WorkerGlobalScope/location
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
11.5+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
Returns
workerGlobal
's
WorkerLocation
object.
workerGlobal
navigator
WorkerGlobalScope/navigator
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
11.5+
Edge
79+
Edge (Legacy)
17+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
Returns
workerGlobal
's
WorkerNavigator
object.
workerGlobal
importScripts
(...
urls
WorkerGlobalScope/importScripts
Support in all current engines.
Firefox
4+
Safari
4+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
Fetches each
URL
in
urls
, executes them one-by-one in the order they
are passed, and then returns (or throws if something went amiss).
The
self
attribute must return the
WorkerGlobalScope
object itself.
The
location
attribute must return the
WorkerLocation
object whose associated
WorkerGlobalScope
object
is
the
WorkerGlobalScope
object.
While the
WorkerLocation
object is created after the
WorkerGlobalScope
object, this is not problematic as it cannot be observed from
script.
The following are the
event handlers
(and their corresponding
event handler event types
) that must be supported,
as
event handler IDL attributes
, by objects implementing the
WorkerGlobalScope
interface:
Event handler
Event handler event type
onerror
WorkerGlobalScope/error_event
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
11.5+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
error
onlanguagechange
WorkerGlobalScope/languagechange_event
Support in all current engines.
Firefox
74+
Safari
4+
Chrome
4+
Opera
11.5+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
37+
Samsung Internet
Opera Android
languagechange
onoffline
WorkerGlobalScope/offline_event
Firefox
29+
Safari
8+
Chrome
No
Opera
Edge
No
Edge (Legacy)
Internet Explorer
No
Firefox Android
Safari iOS
Chrome Android
WebView Android
Samsung Internet
Opera Android
offline
ononline
WorkerGlobalScope/online_event
Firefox
29+
Safari
8+
Chrome
No
Opera
Edge
No
Edge (Legacy)
Internet Explorer
No
Firefox Android
Safari iOS
Chrome Android
WebView Android
Samsung Internet
Opera Android
online
onrejectionhandled
rejectionhandled
onunhandledrejection
unhandledrejection
10.2.1.2
Dedicated workers and the
DedicatedWorkerGlobalScope
interface
DedicatedWorkerGlobalScope
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
Global
=(
Worker
DedicatedWorker
),
Exposed
DedicatedWorker
interface
DedicatedWorkerGlobalScope
WorkerGlobalScope
Replaceable
readonly
attribute
DOMString
name
undefined
postMessage
any
message
sequence
object
transfer
);
undefined
postMessage
any
message
optional
StructuredSerializeOptions
options
= {});
undefined
close
();
};
DedicatedWorkerGlobalScope
includes
MessageEventTarget
DedicatedWorkerGlobalScope
objects have an associated
inside port
(a
MessagePort
). This port is part of a channel that is set up when the worker is
created, but it is not exposed. This object must never be garbage collected before
the
DedicatedWorkerGlobalScope
object.
dedicatedWorkerGlobal
name
DedicatedWorkerGlobalScope/name
Support in all current engines.
Firefox
55+
Safari
12.1+
Chrome
70+
Opera
Edge
79+
Edge (Legacy)
18
Internet Explorer
No
Firefox Android
Safari iOS
Chrome Android
WebView Android
Samsung Internet
Opera Android
Returns
dedicatedWorkerGlobal
's
name
, i.e. the value given to the
Worker
constructor. Primarily useful for debugging.
dedicatedWorkerGlobal
postMessage
message
[,
transfer
])
DedicatedWorkerGlobalScope/postMessage
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
dedicatedWorkerGlobal
postMessage
message
[, {
transfer
} ])
Clones
message
and transmits it to the
Worker
object associated
with
dedicatedWorkerGlobal
transfer
can be passed as a list of objects
that are to be transferred rather than cloned.
dedicatedWorkerGlobal
close
()
DedicatedWorkerGlobalScope/close
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
Aborts
dedicatedWorkerGlobal
The
name
getter steps are to return
this
's
name
. Its value
represents the name given to the worker using the
Worker
constructor, used primarily
for debugging purposes.
The
postMessage(
message
transfer
and
postMessage(
message
options
methods on
DedicatedWorkerGlobalScope
objects act as
if, when invoked, it immediately invoked the respective
postMessage(
message
transfer
and
postMessage(
message
options
on the port, with the same arguments, and returned the same return
value.
To
close a worker
, given a
workerGlobal
, run these steps:
Discard any
tasks
that have been added to
workerGlobal
's
relevant agent
's
event loop
's
task
queues
Set
workerGlobal
's
closing
flag to true. (This prevents any further tasks from being queued.)
The
close()
method steps are to
close a worker
given
this
10.2.1.3
Shared workers and the
SharedWorkerGlobalScope
interface
SharedWorkerGlobalScope
Support in all current engines.
Firefox
29+
Safari
16+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
Safari iOS
16+
Chrome Android
WebView Android
37+
Samsung Internet
Opera Android
11+
Global
=(
Worker
SharedWorker
),
Exposed
SharedWorker
interface
SharedWorkerGlobalScope
WorkerGlobalScope
Replaceable
readonly
attribute
DOMString
name
undefined
close
();
attribute
EventHandler
onconnect
};
SharedWorkerGlobalScope
object has associated
constructor origin
(an
origin
),
constructor
URL
(a
URL record
), and
credentials
(a
credentials mode
), and
extended lifetime
(a boolean).
They are initialized when the
SharedWorkerGlobalScope
object is created, in the
run a worker
algorithm.
Shared workers receive message ports through
connect
events on their
SharedWorkerGlobalScope
object for each
connection.
sharedWorkerGlobal
name
SharedWorkerGlobalScope/name
Support in all current engines.
Firefox
29+
Safari
16+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
Safari iOS
16+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
Returns
sharedWorkerGlobal
's
name
, i.e. the value given to the
SharedWorker
constructor. Multiple
SharedWorker
objects can correspond
to the same shared worker (and
SharedWorkerGlobalScope
), by reusing the same
name.
sharedWorkerGlobal
close
()
SharedWorkerGlobalScope/close
Support in all current engines.
Firefox
29+
Safari
16+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
Safari iOS
16+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
Aborts
sharedWorkerGlobal
The
name
getter steps are to return
this
's
name
. Its value
represents the name that can be used to obtain a reference to the worker using the
SharedWorker
constructor.
The
close()
method steps are to
close a
worker
given
this
The following are the
event handlers
(and their corresponding
event handler event types
) that must be supported,
as
event handler IDL attributes
, by objects implementing the
SharedWorkerGlobalScope
interface:
Event handler
Event handler event type
onconnect
SharedWorkerGlobalScope/connect_event
Support in all current engines.
Firefox
29+
Safari
16+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
Safari iOS
16+
Chrome Android
WebView Android
37+
Samsung Internet
Opera Android
11+
connect
10.2.2
The event loop
worker event loop
's
task queues
only have
events, callbacks, and networking activity as
tasks
. These
worker event loops
are created by the
run a worker
algorithm.
Each
WorkerGlobalScope
object has a
closing
flag, which must be initially
false, but which can get set to true by the algorithms in the processing model
section below.
Once the
WorkerGlobalScope
's
closing
flag is set to true, the
event
loop
's
task queues
must discard any
further
tasks
that would be added to them (tasks already on the
queue are unaffected except where otherwise specified). Effectively, once the
closing
flag is true, timers stop firing,
notifications for all pending background operations are dropped, etc.
10.2.3
The worker's lifetime
Workers communicate with other workers and with
Window
s through
message channels
and their
MessagePort
objects.
Each
WorkerGlobalScope
object
worker global scope
has a list of
the worker's ports
, which consists of all the
MessagePort
objects
that are entangled with another port and that have one (but only one) port owned by
worker
global scope
. This list includes the implicit
MessagePort
in the case of
dedicated workers
Given an
environment settings
object
when creating or obtaining a worker, the
relevant owner to
add
depends on the type of
global
object
specified by
. If
's
global object
is a
WorkerGlobalScope
object (i.e., if we are creating a nested dedicated worker), then the relevant owner is that
global object. Otherwise,
's
global
object
is a
Window
object, and the relevant owner is that
Window
's
associated
Document
A user agent has an
implementation-defined
value, the
between-loads shared
worker timeout
, which is some small amount of time. This represents how long the user agent
allows shared workers to survive while a page is loading, in case that page is going to contact
the shared worker again. Setting this value to greater than zero lets user agents avoid the cost
of restarting a shared worker used by a site when the user is navigating from page to page within
that site.
A typical value for the
between-loads shared worker timeout
might be
5 seconds.
A user agent has an
implementation-defined
value, the
extended lifetime
shared worker timeout
, which is some amount of time. This represents how long the user agent
allows shared workers which the web developer has requested be given an extended lifetime, to
survive and perform work after all of their
owners
have
disappeared. User agents should choose a value that is equal to the longest lifetime that a
service worker can stay alive without any
clients
, and
must not choose a value that is longer than that amount of time.
A typical value for the
extended lifetime shared worker timeout
could
be anywhere from 10 seconds to 5 minutes, depending on the implementation's individual policies
regarding background work being performed by an origin without a user-visible representation.
WorkerGlobalScope
global
is
in extended lifetime
if the following algorithm returns true:
If
global
is not a
SharedWorkerGlobalScope
, then return
false.
If
global
's
extended lifetime
is false,
then return false.
If
global
's
owner set
is
empty
, but has been empty for less than the user agent's
extended lifetime shared
worker timeout
, then return true.
For each
owner
of
global
's
owner set
If
owner
is a
Document
that is
fully active
, then
return false.
In this case
global
will be
actively needed
, but it's not in extended lifetime.
For each
owner
of
global
's
owner set
If
owner
is a
Document
and the amount of time that
owner
that has been non-
fully active
is less than the user agent's
extended lifetime shared worker timeout
, then return true.
If
owner
is a
WorkerGlobalScope
that is
in extended lifetime
, then return true.
Return false.
WorkerGlobalScope
global
is
actively needed
if the following algorithm returns true:
If
global
is
in extended
lifetime
, then return true.
For each
owner
of
global
's
owner set
If
owner
is a
Document
, and
owner
is
fully
active
, then return true.
If
owner
is a
WorkerGlobalScope
that is
actively needed
, then return true.
Return false.
WorkerGlobalScope
global
is
protected
if the following algorithm returns true:
If
global
is not
actively needed
then return false.
If
global
is
in extended
lifetime
, then return true.
If
global
is a
SharedWorkerGlobalScope
, then return true.
If
global
's
the worker's ports
is not
empty
, then return true.
If
global
has outstanding timers, database transactions, or network
connections, then return true.
Return false.
WorkerGlobalScope
global
is
permissible
if the following algorithm returns true:
If
global
's
owner set
is not
empty
, then return true.
If
global
is
in extended
lifetime
, then return true.
If all of the following are true:
global
is a
SharedWorkerGlobalScope
global
's
owner set
has been
empty
for no more than the user agent's
between-loads shared worker
timeout
; and
the user agent has a
navigable
whose
active
document
is not
completely loaded
then return true.
Return false.
The following relationships hold between these terms:
Every
WorkerGlobalScope
that is
in extended lifetime
is
actively
needed
protected
, and
permissible
Every
WorkerGlobalScope
that is
actively
needed
or
protected
is
permissible
Every
WorkerGlobalScope
that is
protected
is
actively needed
However, the converses do not always hold:
WorkerGlobalScope
can be
actively
needed
but not
protected
, if it's a dedicated
worker with no outstanding async work that is still performing computation on behalf of a fully
active owner, but whose corresponding
Worker
object has been garbage collected.
Because of the garbage collection
, the
ports
collection is empty, so it is no longer protected.
However, its event loop has not yet yielded to
empty its owner set
, so it is still
actively needed.
WorkerGlobalScope
can be
permissible
but not
protected
or
actively needed
, if all the
Document
s in its
transitive set of owners are in
bfcache
, or if it's a
SharedWorkerGlobalScope
with no current owners being kept alive for the duration of
the
between-loads shared worker timeout
The
between-loads shared worker timeout
only influences the definition of
permissible
, not
protected
, and so implementations are not required to keep shared workers alive
for that duration. Rather, they are required to close shared workers after the timeout is
reached.
In contrast, the
extended lifetime shared worker timeout
does influence the
definition of
protected
, so implementations are required
to keep shared workers alive (and not suspended) for that duration.
WorkerGlobalScope
global
is
suspendable
if the following algorithm returns true:
If
global
is
actively needed
, then
return false.
If
global
is
permissible
, then return
true.
Return false.
These concepts are used elsewhere in the specification's normative requirements as
follows:
Workers get
closed as orphans
between when
they stop being
protected
and when they stop being
permissible
Workers that have been closed, but keep executing,
can be terminated
at the user agent's discretion, once
they stop being
actively needed
Workers get
suspended or un-suspended
based on
whether they are
suspendable
10.2.4
Processing model
When a user agent is to
run a worker
for a script with
Worker
or
SharedWorker
object
worker
URL
url
environment settings object
outside settings
MessagePort
outside port
, and a
WorkerOptions
dictionary
options
, it must
run the following steps.
Let
is shared
be true if
worker
is a
SharedWorker
object, and false otherwise.
Let
owner
be the
relevant owner to add
given
outside
settings
Let
unsafeWorkerCreationTime
be the
unsafe shared current
time
Let
agent
be the result of
obtaining a dedicated/shared worker agent
given
outside settings
and
is shared
. Run the rest of these steps in that agent.
Let
realm execution context
be the result of
creating a new realm
given
agent
and the following customizations:
For the global object, if
is shared
is true, create a new
SharedWorkerGlobalScope
object. Otherwise, create a new
DedicatedWorkerGlobalScope
object.
Let
worker global scope
be the
global
object
of
realm execution context
's Realm component.
This is the
DedicatedWorkerGlobalScope
or
SharedWorkerGlobalScope
object created in the previous step.
Set up a worker environment settings object
with
realm execution
context
outside settings
, and
unsafeWorkerCreationTime
, and let
inside settings
be the result.
Set
worker global scope
's
name
to
options
["
name
"].
Append
owner
to
worker global
scope
's
owner set
If
is shared
is true, then:
Set
worker global scope
's
constructor origin
to
outside settings
's
origin
Set
worker global scope
's
constructor URL
to
url
Set
worker global scope
's
type
to
options
["
type
"].
Set
worker global scope
's
credentials
to
options
["
credentials
"].
Set
worker global scope
's
extended lifetime
to
options
["
extendedLifetime
"].
Let
destination
be "
sharedworker
" if
is
shared
is true, and "
worker
" otherwise.
Obtain
script
by switching on
options
["
type
"]:
classic
Fetch a classic worker script
given
url
outside
settings
destination
inside settings
, and with
onComplete
and
performFetch
as defined below.
module
Fetch a module worker script graph
given
url
outside
settings
destination
, the value of the
credentials
member of
options
inside settings
, and with
onComplete
and
performFetch
as defined below.
In both cases, let
performFetch
be the following
perform the fetch hook
given
request
isTopLevel
, and
processCustomFetchResponse
If
isTopLevel
is false,
fetch
request
with
processResponseConsumeBody
set to
processCustomFetchResponse
, and abort these steps.
Set
request
's
reserved
client
to
inside settings
Fetch
request
with
processResponseConsumeBody
set to the following steps
given
response
response
and null, failure,
or a
byte sequence
bodyBytes
Set
worker global scope
's
url
to
response
's
url
Set
inside settings
's
creation URL
to
response
's
url
Initialize worker global scope's
policy container
given
worker global scope
response
, and
inside settings
If the
Run CSP initialization for a global object
algorithm returns
Blocked
" when executed upon
worker global scope
, set
response
to a
network error
[CSP]
If
worker global scope
's
embedder policy
's
value
is
compatible with cross-origin
isolation
and
is shared
is true, then set
agent
's
agent
cluster
's
cross-origin isolation
mode
to "
logical
" or "
concrete
". The one chosen is
implementation-defined
This really ought to be set when the agent cluster is created, which requires
a redesign of this section.
If the result of
checking a
global object's embedder policy
with
worker global scope
outside
settings
, and
response
is false, then set
response
to a
network error
Set
worker global scope
's
cross-origin isolated
capability
to true if
agent
's
agent cluster
's
cross-origin isolation mode
is "
concrete
".
If
is shared
is false and
owner
's
cross-origin isolated
capability
is false, then set
worker global scope
's
cross-origin isolated
capability
to false.
If
is shared
is false and
response
's
url
's
scheme
is "
data
", then set
worker global scope
's
cross-origin isolated
capability
to false.
This is a conservative default for now, while we figure out how workers in
general, and
data:
URL workers in particular (which are
cross-origin from their owner), will be treated in the context of permissions policies. See
w3c/webappsec-permissions-policy
issue #207
for more details.
Run
processCustomFetchResponse
with
response
and
bodyBytes
In both cases, let
onComplete
given
script
be the following steps:
If
script
is null or if
script
's
error to rethrow
is non-null, then:
Queue a global task
on the
DOM manipulation task source
given
worker
's
relevant global object
to
fire an event
named
error
at
worker
Run the
environment discarding steps
for
inside settings
Abort these steps.
Associate
worker
with
worker global scope
Let
inside port
be a
new
MessagePort
object in
inside settings
's
realm
If
is shared
is false, then:
Set
inside port
's
message event target
to
worker global
scope
Set
worker global scope
's
inside port
to
inside
port
Entangle
outside port
and
inside port
Create a new
WorkerLocation
object and associate it with
worker global
scope
Closing orphan workers
: Start monitoring
worker global scope
such that no sooner than it stops being
protected
, and no later than it stops being
permissible
worker global scope
's
closing
flag is set to true.
Suspending workers
: Start monitoring
worker
global scope
, such that whenever
worker global scope
's
closing
flag is false and it is
suspendable
, the user agent suspends execution of script in
worker global scope
until such time as either the
closing
flag switches to true or
worker
global scope
stops being
suspendable
Set
inside settings
's
execution ready flag
If
script
is a
classic script
, then
run the classic script
script
. Otherwise, it is a
module
script
run the module script
script
In addition to the usual possibilities of returning a value or failing due to
an exception, this could be
prematurely aborted
by
the
terminate a worker
algorithm defined below.
Enable
outside port
's
port message queue
If
is shared
is false, enable the
port message queue
of the worker's implicit port.
If
is shared
is true, then
queue a global task
on the
DOM
manipulation task source
given
worker global scope
to
fire an event
named
connect
at
worker global scope
, using
MessageEvent
, with the
data
attribute
initialized to the empty string, the
ports
attribute
initialized to a new
frozen array
containing
inside port
, and the
source
attribute initialized to
inside
port
Enable the
client message queue
of the
ServiceWorkerContainer
object whose associated
service worker client
is
worker global scope
's
relevant settings object
Event loop
: Run the
responsible
event loop
specified by
inside settings
until it is destroyed.
The handling of events or the execution of callbacks by
tasks
run by the
event loop
might get
prematurely aborted
by the
terminate a
worker
algorithm defined below.
The worker processing model remains on this step until the event loop is
destroyed, which happens after the
closing
flag is set to true, as described in the
event loop
processing model.
Clear
the
worker global scope
's
map of active timers
Disentangle all the ports in the list of
the worker's ports
Empty
worker global scope
's
owner set
When a user agent is to
terminate a worker
, it must run the following steps
in parallel
with the worker's main loop (the "
run a worker
" processing
model defined above):
Set the worker's
WorkerGlobalScope
object's
closing
flag to true.
If there are any
tasks
queued in the
WorkerGlobalScope
object's
relevant agent
's
event loop
's
task
queues
, discard them without processing them.
Abort the script
currently running in the
worker.
If the worker's
WorkerGlobalScope
object is actually a
DedicatedWorkerGlobalScope
object (i.e. the worker is a dedicated worker), then
empty the
port message queue
of the port that the worker's implicit port is
entangled with.
User agents may invoke the
terminate a worker
algorithm when a worker stops being
actively needed
and
the worker continues executing even after its
closing
flag was set to true.
10.2.5
Runtime script errors
Whenever an uncaught runtime script error occurs in one of the worker's scripts, if the error
did not occur while handling a previous script error, the user agent will
report
it for the worker's
WorkerGlobalScope
object.
10.2.6
Creating workers
10.2.6.1
The
AbstractWorker
mixin
interface
mixin
AbstractWorker
attribute
EventHandler
onerror
};
The following are the
event handlers
(and their corresponding
event handler event types
) that must be supported,
as
event handler IDL attributes
, by objects implementing the
AbstractWorker
interface:
Event handler
Event handler event type
onerror
ServiceWorker/error_event
Support in all current engines.
Firefox
44+
Safari
11.1+
Chrome
40+
Opera
Edge
79+
Edge (Legacy)
17+
Internet Explorer
No
Firefox Android
Safari iOS
Chrome Android
WebView Android
Samsung Internet
Opera Android
SharedWorker/error_event
Support in all current engines.
Firefox
29+
Safari
16+
Chrome
5+
Opera
10.6+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
33+
Safari iOS
16+
Chrome Android
No
WebView Android
Samsung Internet
4.0–5.0
Opera Android
11–14
Worker/error_event
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
error
10.2.6.2
Script settings for workers
To
set up a worker environment settings object
, given a
JavaScript execution
context
execution context
, an
environment settings object
outside settings
, and a number
unsafeWorkerCreationTime
Let
realm
be the value of
execution context
's Realm
component.
Let
worker global scope
be
realm
's
global object
Let
origin
be a unique
opaque origin
if
worker global scope
's
url
's
scheme
is "
data
"; otherwise
outside settings
's
origin
Let
settings object
be a new
environment settings object
whose algorithms
are defined as follows:
The
realm execution context
Return
execution context
The
module map
Return
worker global scope
's
module map
The
API base URL
Return
worker global scope
's
url
The
origin
Return
origin
The
has cross-site
ancestry
If
outside settings
's
has cross-site ancestor
is
true, then return true.
If
worker global scope
's
url
's
scheme
is "
data
", then return
true.
Return false.
The
policy container
Return
worker global scope
's
policy container
The
cross-origin
isolated capability
Return
worker global scope
's
cross-origin isolated
capability
The
time origin
Return the result of
coarsening
unsafeWorkerCreationTime
with
worker global scope
's
cross-origin isolated
capability
Set
settings object
's
id
to a new
unique opaque string,
creation URL
to
worker global scope
's
url
top-level creation URL
to null,
target browsing context
to
null, and
active service worker
to null.
If
worker global scope
is a
DedicatedWorkerGlobalScope
object,
then set
settings object
's
top-level origin
to
outside
settings
's
top-level origin
Otherwise, set
settings object
's
top-level origin
to an
implementation-defined
value.
See
Client-Side
Storage Partitioning
for the latest on properly defining this.
Set
realm
's [[HostDefined]] field to
settings object
Return
settings object
10.2.6.3
Dedicated workers and the
Worker
interface
Worker
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
2+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
Exposed
=(
Window
DedicatedWorker
SharedWorker
)]
interface
Worker
EventTarget
constructor
((
TrustedScriptURL
or
USVString
scriptURL
optional
WorkerOptions
options
= {});
undefined
terminate
();
undefined
postMessage
any
message
sequence
object
transfer
);
undefined
postMessage
any
message
optional
StructuredSerializeOptions
options
= {});
};
dictionary
WorkerOptions
DOMString
name
= "";
WorkerType
type
= "classic";
RequestCredentials
credentials
= "same-origin"; // credentials is only used if type is "module"
};
enum
WorkerType
"classic"
"module"
};
Worker
includes
AbstractWorker
Worker
includes
MessageEventTarget
worker
= new
Worker
scriptURL
[,
options
])
Worker/Worker
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
Returns a new
Worker
object.
scriptURL
will be fetched and executed
in the background, creating a new global environment for which
worker
represents the
communication channel.
options
can contain the following values:
name
can be used to define the
name
of that global environment, primarily for
debugging purposes.
type
can be used to load the new
global environment from
scriptURL
as a JavaScript module, by setting it to the value
module
".
credentials
can be used to
specify how
scriptURL
is fetched, but only if
type
is set to "
module
".
worker
terminate
()
Worker/terminate
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
2+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
Aborts
worker
's associated global environment.
worker
postMessage
message
[,
transfer
])
Worker/postMessage
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
2+
Opera
10.6+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
11+
worker
postMessage
message
[, {
transfer
} ])
Clones
message
and transmits it to
worker
's global environment.
transfer
can be passed as a list of objects that are to be transferred rather than
cloned.
Each
Worker
object has an associated
outside port
(a
MessagePort
). This port is part of a channel that is set up when the worker is
created, but it is not exposed. This object must never be garbage collected before the
Worker
object.
The
terminate()
method steps are to
terminate a worker
given
this
's worker.
The
postMessage(
message
transfer
and
postMessage(
message
options
methods on
Worker
objects act as if, when invoked,
they immediately invoked the respective
postMessage(
message
transfer
and
postMessage(
message
options
on
this
's
outside port
, with the same
arguments, and returned the same return value.
The
postMessage()
method's first argument can be structured data:
worker
postMessage
({
opcode
'activate'
device
1938
parameters
23
102
]});
The
new Worker(
scriptURL
options
constructor steps are:
Let
compliantScriptURL
be the result of invoking the
get trusted type compliant string
algorithm with
TrustedScriptURL
this
's
relevant global
object
scriptURL
, "
Worker constructor
", and "
script
".
Let
outsideSettings
be
this
's
relevant settings
object
Let
workerURL
be the result of
encoding-parsing a URL
given
compliantScriptURL
, relative to
outsideSettings
Any
same-origin
URL (including
blob:
URLs) can be used.
data:
URLs can also be used, but they create a worker with an
opaque origin
If
workerURL
is failure, then throw a
SyntaxError
DOMException
Let
outsidePort
be a
new
MessagePort
in
outsideSettings
's
realm
Set
outsidePort
's
message event target
to
this
Set
this
's
outside port
to
outsidePort
Let
worker
be
this
Run this step
in parallel
Run a worker
given
worker
workerURL
outsideSettings
outsidePort
, and
options
10.2.6.4
Shared workers and the
SharedWorker
interface
SharedWorker
Support in all current engines.
Firefox
29+
Safari
16+
Chrome
5+
Opera
10.6+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
33+
Safari iOS
16+
Chrome Android
No
WebView Android
Samsung Internet
4.0–5.0
Opera Android
11–14
Exposed
Window
interface
SharedWorker
EventTarget
constructor
((
TrustedScriptURL
or
USVString
scriptURL
optional
DOMString
or
SharedWorkerOptions
options
= {});
readonly
attribute
MessagePort
port
};
SharedWorker
includes
AbstractWorker
dictionary
SharedWorkerOptions
WorkerOptions
boolean
extendedLifetime
false
};
sharedWorker
= new
SharedWorker
scriptURL
[,
name
])
SharedWorker/SharedWorker
Support in all current engines.
Firefox
29+
Safari
16+
Chrome
5+
Opera
10.6+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
33+
Safari iOS
16+
Chrome Android
No
WebView Android
Samsung Internet
4.0–5.0
Opera Android
11–14
Returns a new
SharedWorker
object.
scriptURL
will be fetched and
executed in the background, creating a new global environment for which
sharedWorker
represents the communication channel.
name
can be used to define the
name
of that global environment.
sharedWorker
= new
SharedWorker
scriptURL
[,
options
])
Returns a new
SharedWorker
object.
scriptURL
will be fetched and
executed in the background, creating a new global environment for which
sharedWorker
represents the communication channel.
options
can contain the following values:
name
can be used to define the
name
of that global environment.
type
can be used to load the new global
environment from
scriptURL
as a JavaScript module, by setting it to the value "
module
".
credentials
can be used to specify
how
scriptURL
is fetched, but only if
type
is set to "
module
".
extendedLifetime
can be
set to request that the newly-created global environment be given extra time to perform its
operations even after all of its
owners
have disappeared. This
can be useful, for example, for performing asynchronous work after page unload.
Note that attempting to construct a shared worker with
options
whose
type
credentials
, or
extendedLifetime
values mismatch those
of an existing shared worker with the same
constructor URL
and
name
, will cause the returned
sharedWorker
to fire an
error
event and not connect
to the existing shared worker.
sharedWorker
port
SharedWorker/port
Support in all current engines.
Firefox
29+
Safari
16+
Chrome
5+
Opera
10.6+
Edge
79+
Edge (Legacy)
Internet Explorer
No
Firefox Android
33+
Safari iOS
16+
Chrome Android
No
WebView Android
Samsung Internet
4.0–5.0
Opera Android
11–14
Returns
sharedWorker
's
MessagePort
object which can be used to
communicate with the global environment.
A user agent has an associated
shared worker manager
which is the result of
starting a new parallel queue
Each user agent has a single
shared worker manager
for simplicity.
Implementations could use one per
origin
; that would not be observably different and
enables more concurrency.
Each
SharedWorker
has a
port
, a
MessagePort
set when the object is created.
The
port
getter steps are to return
this
's
port
The
new
SharedWorker(
scriptURL
options
constructor steps are:
Let
compliantScriptURL
be the result of invoking the
get trusted type compliant string
algorithm with
TrustedScriptURL
this
's
relevant global
object
scriptURL
, "
SharedWorker constructor
", and
script
".
If
options
is a
DOMString
, set
options
to a new
WorkerOptions
dictionary whose
name
member is set to the value of
options
and
whose other members are set to their default values.
Let
outsideSettings
be
this
's
relevant settings
object
Let
urlRecord
be the result of
encoding-parsing a URL
given
compliantScriptURL
, relative to
outsideSettings
Any
same-origin
URL (including
blob:
URLs) can be used.
data:
URLs can also be used, but they create a worker with an
opaque origin
If
urlRecord
is failure, then throw a
SyntaxError
DOMException
Let
outsidePort
be a
new
MessagePort
in
outsideSettings
's
realm
Set
this
's
port
to
outsidePort
Let
callerIsSecureContext
be true if
outsideSettings
is a
secure context
; otherwise, false.
Let
outsideStorageKey
be the result of running
obtain a storage key for
non-storage purposes
given
outsideSettings
Let
worker
be
this
Enqueue the following steps
to the
shared worker manager
Let
workerGlobalScope
be null.
For each
scope
in the list of all
SharedWorkerGlobalScope
objects:
Let
workerStorageKey
be the result of running
obtain a storage key
for non-storage purposes
given
scope
's
relevant settings
object
If all of the following are true:
workerStorageKey
equals
outsideStorageKey
scope
's
closing
flag is
false;
scope
's
constructor URL
equals
urlRecord
; and
scope
's
name
equals
options
["
name
"],
then:
Set
workerGlobalScope
to
scope
Break
data:
URLs create a worker with an
opaque origin
. Both the
constructor origin
and
constructor URL
are
compared so the same
data:
URL can be used within an
origin
to get to the same
SharedWorkerGlobalScope
object, but cannot
be used to bypass the
same origin
restriction.
If
workerGlobalScope
is not null, but the user agent has been configured to
disallow communication between the worker represented by the
workerGlobalScope
and
the
scripts
whose
settings object
is
outsideSettings
then set
workerGlobalScope
to null.
For example, a user agent could have a development mode that isolates a
particular
top-level traversable
from all other pages, and scripts in that
development mode could be blocked from connecting to shared workers running in the normal
browser mode.
If
workerGlobalScope
is not null, and any of the following are true:
workerGlobalScope
's
type
is not equal to
options
["
type
"];
workerGlobalScope
's
credentials
is not equal to
options
["
credentials
"];
or
workerGlobalScope
's
extended lifetime
is not
equal to
options
["
extendedLifetime
"],
then:
Queue a global task
on the
DOM manipulation task source
given
worker
's
relevant global object
to
fire an event
named
error
at
worker
Abort these steps.
If
workerGlobalScope
is not null:
Let
insideSettings
be
workerGlobalScope
's
relevant
settings object
Let
workerIsSecureContext
be true if
insideSettings
is a
secure context
; otherwise, false.
If
workerIsSecureContext
is not
callerIsSecureContext
Queue a global task
on the
DOM manipulation task source
given
worker
's
relevant global object
to
fire an event
named
error
at
worker
Abort these steps.
Associate
worker
with
workerGlobalScope
Let
insidePort
be a
new
MessagePort
in
insideSettings
's
realm
Entangle
outsidePort
and
insidePort
Queue a global task
on the
DOM manipulation task source
given
workerGlobalScope
to
fire an event
named
connect
at
workerGlobalScope
, using
MessageEvent
, with the
data
attribute initialized to the empty string, the
ports
attribute initialized to a new
frozen array
containing only
insidePort
, and the
source
attribute initialized to
insidePort
Append
the
relevant owner to add
given
outsideSettings
to
workerGlobalScope
's
owner set
Otherwise,
in parallel
run a worker
given
worker
urlRecord
outsideSettings
outsidePort
, and
options
10.2.7
Concurrent hardware capabilities
interface
mixin
NavigatorConcurrentHardware
readonly
attribute
unsigned
long
long
hardwareConcurrency
};
self
navigator
hardwareConcurrency
Navigator/hardwareConcurrency
Firefox
48+
Safari
10.1–11
Chrome
37+
Opera
Edge
79+
Edge (Legacy)
15+
Internet Explorer
No
Firefox Android
Safari iOS
Chrome Android
WebView Android
Samsung Internet
Opera Android
Navigator/hardwareConcurrency
Firefox
48+
Safari
10.1–11
Chrome
37+
Opera
Edge
79+
Edge (Legacy)
15+
Internet Explorer
No
Firefox Android
Safari iOS
Chrome Android
WebView Android
Samsung Internet
Opera Android
Returns the number of logical processors potentially available to the user agent.
The
navigator.hardwareConcurrency
attribute's
getter must return a number between 1 and the number of logical processors potentially available
to the user agent. If this cannot be determined, the getter must return 1.
User agents should err toward exposing the number of logical processors available, using lower
values only in cases where there are user-agent specific limits in place (such as a limitation
on the number of
workers
that can be created) or when the user agent
desires to limit fingerprinting possibilities.
10.3
APIs available to workers
10.3.1
Importing scripts and libraries
The
importScripts(...
urls
method steps are:
Let
urlStrings
be « ».
For each
url
of
urls
Append
the result of invoking the
get trusted type compliant string
algorithm with
TrustedScriptURL
this
's
relevant global
object
url
, "
WorkerGlobalScope importScripts
", and
script
" to
urlStrings
Import scripts into worker global scope
given
this
and
urlStrings
To
import scripts into worker global scope
, given a
WorkerGlobalScope
object
worker global scope
, a
list
of
scalar value strings
urls
, and an optional
perform the fetch hook
performFetch
If
worker global scope
's
type
is "
module
", throw a
TypeError
exception.
Let
settings object
be the
current settings object
If
urls
is empty, return.
Let
urlRecords
be « ».
For each
url
of
urls
Let
urlRecord
be the result of
encoding-parsing a URL
given
url
, relative to
settings object
If
urlRecord
is failure, then throw a
SyntaxError
DOMException
Append
urlRecord
to
urlRecords
For each
urlRecord
of
urlRecords
Fetch a classic worker-imported script
given
urlRecord
and
settings object
, passing along
performFetch
if provided. If this
succeeds, let
script
be the result. Otherwise, rethrow the exception.
Run the classic script
script
, with
rethrow errors
set to true.
script
will run until it either returns, fails to parse, fails to
catch an exception, or gets
prematurely aborted
by the
terminate a worker
algorithm defined above.
If an exception was thrown or if the script was
prematurely aborted
, then abort all these steps, letting the exception or
aborting continue to be processed by the calling
script
Service Workers
is an example of a specification that runs this
algorithm with its own
perform the fetch
hook
[SW]
10.3.2
The
WorkerNavigator
interface
WorkerNavigator
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
12.1+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
12.1+
The
navigator
attribute of the
WorkerGlobalScope
interface must return an instance of the
WorkerNavigator
interface, which represents the identity and state of the user agent
(the client):
Exposed
Worker
interface
WorkerNavigator
{};
WorkerNavigator
includes
NavigatorID
WorkerNavigator
includes
NavigatorLanguage
WorkerNavigator
includes
NavigatorOnLine
WorkerNavigator
includes
NavigatorConcurrentHardware
10.3.3
The
WorkerLocation
interface
WorkerLocation
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
12.1+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
12.1+
WorkerLocation/toString
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
15+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
37+
Samsung Internet
Opera Android
14+
Exposed
Worker
interface
WorkerLocation
stringifier
readonly
attribute
USVString
href
readonly
attribute
USVString
origin
readonly
attribute
USVString
protocol
readonly
attribute
USVString
host
readonly
attribute
USVString
hostname
readonly
attribute
USVString
port
readonly
attribute
USVString
pathname
readonly
attribute
USVString
readonly
attribute
USVString
hash
};
WorkerLocation
object has an associated
WorkerGlobalScope
object
(a
WorkerGlobalScope
object).
WorkerLocation/href
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
12.1+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
12.1+
The
href
getter steps are to return
this
's
WorkerGlobalScope
object
's
url
serialized
WorkerLocation/origin
Support in all current engines.
Firefox
29+
Safari
10+
Chrome
38+
Opera
Edge
79+
Edge (Legacy)
14+
Internet Explorer
No
Firefox Android
Safari iOS
Chrome Android
WebView Android
Samsung Internet
Opera Android
The
origin
getter steps are to return the
serialization
of
this
's
WorkerGlobalScope
object
's
url
's
origin
WorkerLocation/protocol
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
12.1+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
12.1+
The
protocol
getter steps are to return
this
's
WorkerGlobalScope
object
's
url
's
scheme
, followed by "
".
WorkerLocation/host
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
12.1+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
12.1+
The
host
getter steps are:
Let
url
be
this
's
WorkerGlobalScope
object
's
url
If
url
's
host
is null, return the empty
string.
If
url
's
port
is null, return
url
's
host
serialized
Return
url
's
host
serialized
, followed by "
" and
url
's
port
serialized
WorkerLocation/hostname
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
12.1+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
12.1+
The
hostname
getter steps are:
Let
host
be
this
's
WorkerGlobalScope
object
's
url
's
host
If
host
is null, return the empty string.
Return
host
serialized
WorkerLocation/port
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
12.1+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
12.1+
The
port
getter steps are:
Let
port
be
this
's
WorkerGlobalScope
object
's
url
's
port
If
port
is null, return the empty string.
Return
port
serialized
WorkerLocation/pathname
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
12.1+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
12.1+
The
pathname
getter steps are to return the result
of
URL path serializing
this
's
WorkerGlobalScope
object
's
url
WorkerLocation/search
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
12.1+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
12.1+
The
getter steps are:
Let
query
be
this
's
WorkerGlobalScope
object
's
url
's
query
If
query
is either null or the empty string, return the empty string.
Return "
", followed by
query
WorkerLocation/hash
Support in all current engines.
Firefox
3.5+
Safari
4+
Chrome
4+
Opera
12.1+
Edge
79+
Edge (Legacy)
12+
Internet Explorer
10+
Firefox Android
Safari iOS
5+
Chrome Android
WebView Android
Samsung Internet
Opera Android
12.1+
The
hash
getter steps are:
Let
fragment
be
this
's
WorkerGlobalScope
object
's
url
's
fragment
If
fragment
is either null or the empty string, return the empty string.
Return "
", followed by
fragment