Service workers run within their own context or thread outside the UI. Because the service worker thread is separate from the UI, it does not have access to the DOM.
The service worker scope is event driven, meaning the platform (browser or operating system, depending on your point of view) initiates the service worker. When the service worker initiates, it does so with the intent of responding to an event, such as a web page opening, a push notification, or another event.
The process stays alive long enough to service the need. This time is determined by the browser and varies by platform. There is no fixed time defined in the service worker specification.