Background Task Mode¶
Gecko supports running privileged JavaScript in a special headless “background task” mode. Background task mode is intended to be used for periodic maintenance tasks. The first consumer will be checking for updates, even when Firefox is not running.
Support for background task mode is gated on the build flag MOZ_BACKGROUNDTASKS .
Adding a new background task¶
Background tasks are invoked with —backgroundtask TASKNAME . Tasks must be packaged at build time; the background task runtime looks for regular JSM modules in the following locations (in order):
- (App-specific) resource:///modules/backgroundtasks/BackgroundTask_TASKNAME.sys.mjs
- (Toolkit/general) resource://gre/modules//backgroundtasks/BackgroundTask_TASKNAME.sys.mjs
To add a new background task, add to your moz.build file a stanza like:
EXTRA_JS_MODULES.backgroundtasks += [ "BackgroundTask_TASKNAME.sys.mjs", ]
Implementing a background task¶
In BackgroundTask_TASKNAME.sys.mjs , define a function runBackgroundTask that returns a Promise . runBackgroundTask will be awaited and the integer value it resolves to will be used as the exit code of the —backgroundtask TASKNAME invocation. Optionally, runBackgroundTask can take an nsICommandLine instance as a parameter. For example:
export async function runBackgroundTask(commandLine) return Number.parseInt(commandLine.getArgument(0), 10); >
When invoked like —backgroundtask TASKNAME EXITCODE , this task will simply complete with the exit code given on the command line.
Task module can optionally export an integer value called backgroundTaskTimeoutSec , which will control how long the task can run before it times out. If no value is specified, the timeout value stored in the pref toolkit.backgroundtasks.defaultTimeoutSec will be used.
Special exit codes¶
The exit codes 2-4 have special meaning:
- Exit code 2 ( EXIT_CODE.NOT_FOUND ) means the background task with the given TASKNAME was not found or could not be loaded.
- Exit code 3 ( EXIT_CODE.EXCEPTION ) means the background task invocation rejected with an exception.
- Exit code 4 ( EXIT_CODE.TIMEOUT ) means that the background task timed out before it could complete.
See EXIT_CODE for details.
Test-only background tasks¶
There is special support for test-only background tasks. Add to your moz.build file a stanza like:
TESTING_JS_MODULES.backgroundtasks += [ "BackgroundTask_TESTONLYTASKNAME.sys.mjs", ]
Debugging background tasks¶
Background task mode supports using the JavaScript debugger and the Firefox Devtools and Browser Toolbox. When invoked with the command line parameters —jsdebugger (and optionally —wait-for-jsdebugger ), the background task framework will launch a Browser Toolbox, connect to the background task, and pause execution at the first line of the task implementation. The Browser Toolbox is launched with a temporary profile (sibling to the ephemeral temporary profile the background task itself creates.) The Browser Toolbox profile’s preferences are copied from the default browsing profile, allowing to configure devtools preferences. (The —start-debugger-server command line option is also recognized; see the output of firefox —backgroundtask success —attach-console —help for details.)
Invoking background tasks¶
Use BackgroundTasksRunner::RunInDetachedProcess is a helper to open a new background process within Gecko. It automatically manages the configuration 1) to let the new process outlive the launching process and 2) to escape the arguments properly. The function is safe to be called in a non-main process.
Existing background tasks¶
- BackgroundTask_removeDirectory Removes the child directory with the given name and/or child directories with the given postfix, all in the given parent directory. It’s recommended to run it via the corresponding helper function BackgroundTasksRunner::RemoveDirectoryInDetachedProcess . Tests can use toolkit.background_tasks.remove_directory.testing.sleep_ms to see whether a longstanding task can finish the work even after the launching process is closed.
- BackgroundTask_defaultagent Reports telemetry on Windows for the system defaults. See Default Browser Agent for more information.
The background task mode runtime environment¶
Most background tasks run in ephemeral temporary profiles¶
Background tasks are intended for periodic maintenance tasks, especially global/per-installation maintenance tasks. To allow background tasks to run at the same time as regular, headed Firefox browsing sessions, by default they run with an ephemeral temporary profile. This ephemeral profile is deleted when the background task main process exits. Every background task applies the preferences in backgroundtasks/defaults/backgroundtasks.js , but any additional preference configuration must be handled by the individual task. Over time, we anticipate a small library of background task functionality to grow to make it easier to lock and read specific prefs from the default browsing profile, to declare per-installation prefs, etc.
It is possible to run background tasks in non-emphemeral, i.e., persistent, profiles. See Bug 1775132 for details.
Background tasks limit the XPCOM instance graph by default¶
The technical mechanism that keeps background tasks “lightweight” is very simple. XPCOM declares a number of observer notifications for loosely coupling components via the observer service. Some of those observer notifications are declared as category notifications which allow consumers to register themselves in static components.conf registration files (or in now deprecated chrome.manifest files). In background task mode, category notifications are not registered by default.
For Firefox in particular, this means that BrowserContentHandler.sys.mjs is not registered as a command-line-handler. This means that BrowserGlue.sys.mjs is not loaded, and this short circuits regular headed browsing startup.
See the documentation for defining static components for how to change this default behaviour, and Bug 1675848 for details of the implementation.
Most background tasks do not process updates¶
To prevent unexpected interactions between background tasks and the Firefox runtime lifecycle, such as those uncovered by Bug 1736373, most background tasks do not process application updates. The startup process decides whether to process updates in ::ShouldProcessUpdates and the predicate that determines whether a particular background task does process updates is BackgroundTasks::IsUpdatingTaskName .
Background tasks that are launched at shutdown (and that are not updating) do not prevent Firefox from updating. However, this can result in Firefox updating out from underneath a running background task: see this summary of the issue. Generally, background tasks should be minimal and short-lived and are unlikely to launch additional child subprocesses after startup, so they should not witness this issue, but it is still possible. See the diagram below visualizing process lifetimes.
gantt title Background tasks launched at Firefox shutdown dateFormat YYYY-MM-DD axisFormat section Firefox firefox (version N) :2014-01-03, 3d updater :2014-01-06, 1d firefox (version N+1) :2014-01-07, 3d firefox —backgroundtask . (version N) :2014-01-05, 3d
Most background tasks produce console output¶
Background tasks are usually scheduled in situations where their output is not user-visible: by the Windows Task Scheduler, at shutdown, etc. Therefore, it’s usually safe to always produce console output. But some tasks, especially shutdown tasks executed during developer builds, can “pollute” the console even after the Firefox main process has exited. To avoid this, background tasks can opt-in to producing no output; the predicate that determines whether a particular background task does produce output is BackgroundTasks::IsNoOutputTaskName . This predicate can be overridden by providing the —attach-console command line flag or by setting the MOZ_BACKGROUNDTASKS_IGNORE_NO_OUTPUT environment variable to a non-empty value.
The pingsender background task opts to produce no output: see Bug 1736623.
More details¶
Maximum and minimum runtime¶
Background tasks are meant to finish their work in a (very) short time. There are two preferences that control these values globally:
toolkit.backgroundtasks.defaultTimeoutSec (default 10 minutes)¶
Defines the maximum runtime. Once this timeout is exceeded, the shutdown sequence will be started, regardless of the still running JS payload’s state. It is thus recommended, that any potentially long running JS payload adds async shutdown blockers that makes it bail out or checks isInOrBeyondShutdownPhase in appropriate places, otherwise shutdown hangs might occur.
toolkit.backgroundtasks.defaultMinTaskRuntimeMS (default 500 ms)¶
Sets the minimum runtime that even an empty background task will wait before starting its shutdown sequence. The main purpose is to give any asynchronously running startup launch of components sufficient time to complete their startup before we ask them to shutdown. Note that this is wallclock counting from the start of the payload, such that if the background task takes longer for itself, no additional time will be added to the execution. If the background task itself may cause further asynchronous component launches or other processing, it should take care of waiting on them to finish before returning. Note that there is an additional 100 ms delay before we actually launch the task plus the process startup and shutdown overhead, such that even an empty task will take ~800 ms minimum (on a modern Windows laptop) to finish with toolkit.backgroundtasks.defaultMinTaskRuntimeMS == 500 .
Overriding the global preference values¶
Additionally you can control these values on a per-task granularity by having:
export const backgroundTaskTimeoutSec = some seconds>; export const backgroundTaskMinRuntimeMS = some millisecs>;
Видимость страницы API
При переключении между вкладками, web страница переходит в фоновый режим и поэтому не видна пользователю. Page Visibility API предоставляет события, которые вы можете отслеживать, чтобы узнать, когда страница станет видимой или скрытой, а так же возможность наблюдать текущее состояние видимости страницы.
Примечание: The Page Visibility API особенно полезно для сбережения ресурсов и улучшения производительности, позволяя странице остановить выполнение не нужных задач, когда она не видна.
Когда пользователь сворачивает окно или переключается на другую вкладку, API отправляет visibilitychange (en-US) событие обработчикам, что состояние страницы изменилось. Вы можете отследить это событие и выполнить какие-то действия. Например, если ваше app проигрывает видео, его можно поставить на паузу, когда пользователь переключил вкладку (страница ушла в фон), а затем возобновить видео, когда пользователь вернулся на вкладку. Пользователь не теряет место на котором остановил просмотр, звук от видео не конфликтует с аудио новой вкладки, пользователь комфортно просмотреть оба видео.
Состояния видимости для (en-US) такие же как и для родительской страницы. Скрытие используя CSS стили (такие как display: none; ) не вызывают события видимости и не изменяют состояние документа, содержащегося во фрейме.
Использование
Давайте рассмотрим несколько способов использования Page Visibility API.
- На сайте есть слайдер изображений с автопрокруткой, которую можно поставить на паузу, когда пользователь перешёл на другую вкладку
- Приложение выводит информацию в реальном времени, которую можно не обновлять, пока страница не видна, тем самым уменьшить количество запросов на сервер
- Странице нужно понять, когда она должна быть отрисована, так что можно вести точный подсчёт количества просмотров
- Сайту нужно выключить звук, когда устройство в режиме ожидания (пользователь нажал кнопку включения, чтобы погасить экран)
Раньше у разработчиков были не удобные способы. Например, обработка blur (en-US) и focus (en-US) событий на объекте window — помогала узнать когда страница становилась не активной, но это не давало возможность понять когда страница действительно скрыта от пользователя. Page Visibility API решает эту проблему.
Примечание: Когда onblur и onfocus уведомляют, что пользователь переключил окна, это не означает, что оно действительно скрыто. Страница действительно скрыта, когда пользователь переключил вкладки или свернул окно браузера с этой вкладкой.
Policies in place to aid background page performance
Separately from the Page Visibility API, user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs. These may include:
- Most browsers stop sending requestAnimationFrame() callbacks to background tabs or hidden (en-US)s in order to improve performance and battery life.
- Timers such as setTimeout() are throttled in background/inactive tabs to help improve performance. See Reasons for delays longer than specified for more details.
- Budget-based background timeout throttling is now available in modern browsers (Firefox 58+, Chrome 57+), placing an additional limit on background timer CPU usage. This operates in a similar way across modern browsers, with the details being as follows:
- In Firefox, windows in background tabs each have their own time budget in milliseconds — a max and a min value of +50 ms and -150 ms, respectively. Chrome is very similar except that the budget is specified in seconds.
- Windows are subjected to throttling after 30 seconds, with the same throttling delay rules as specified for window timers (again, see Reasons for delays longer than specified). In Chrome, this value is 10 seconds.
- Timer tasks are only permitted when the budget is non-negative.
- Once a timer’s code has finished running, the duration of time it took to execute is subtracted from its window’s timeout budget.
- The budget regenerates at a rate of 10 ms per second, in both Firefox and Chrome.
Some processes are exempt from this throttling behavior. In these cases, you can use the Page Visibility API to reduce the tabs’ performance impact while they’re hidden.
- Tabs which are playing audio are considered foreground and aren’t throttled.
- Tabs running code that’s using real-time network connections (WebSockets and WebRTC) go unthrottled in order to avoid closing these connections timing out and getting unexpectedly closed.
- IndexedDB processes are also left unthrottled in order to avoid timeouts.
Example
View live example (video with sound).
The example, which pauses the video when you switch to another tab and plays again when you return to its tab, was created with the following code:
// Set the name of the hidden property and the change event for visibility var hidden, visibilityChange; if (typeof document.hidden !== "undefined") // Opera 12.10 and Firefox 18 and later support hidden = "hidden"; visibilityChange = "visibilitychange"; > else if (typeof document.msHidden !== "undefined") hidden = "msHidden"; visibilityChange = "msvisibilitychange"; > else if (typeof document.webkitHidden !== "undefined") hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; > var videoElement = document.getElementById("videoElement"); // If the page is hidden, pause the video; // if the page is shown, play the video function handleVisibilityChange() if (document[hidden]) videoElement.pause(); > else videoElement.play(); > > // Warn if the browser doesn't support addEventListener or the Page Visibility API if (typeof document.addEventListener === "undefined" || hidden === undefined) console.log( "This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.", ); > else // Handle page visibility change document.addEventListener(visibilityChange, handleVisibilityChange, false); // When the video pauses, set the title. // This shows the paused videoElement.addEventListener( "pause", function () document.title = "Paused"; >, false, ); // When the video plays, set the title. videoElement.addEventListener( "play", function () document.title = "Playing"; >, false, ); >
Properties added to the Document interface
The Page Visibility API adds the following properties to the Document interface:
Returns true if the page is in a state considered to be hidden to the user, and false otherwise.
A DOMString indicating the document’s current visibility state. Possible values are:
The page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window.
The page’s content is not visible to the user, either due to the document’s tab being in the background or part of a window that is minimized, or because the device’s screen is off.
The page’s content is being prerendered and is not visible to the user. A document may start in the prerender state, but will never switch to this state from any other state, since a document can only prerender once.
Примечание: Not all browsers support prerendering.
The page is in the process of being unloaded from memory.
Примечание: Not all browsers support the unloaded value.
//startSimulation and pauseSimulation defined elsewhere function handleVisibilityChange() if (document.hidden) pauseSimulation(); > else startSimulation(); > > document.addEventListener("visibilitychange", handleVisibilityChange, false);
Specifications
Specification HTML Standard
# dom-document-visibilitystateСовместимость с браузерами
BCD tables only load in the browser
See also
- Description of the Page Visibility API on the IEBlog.
- Description of the Page Visibility API by Google
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on 6 янв. 2024 г. by MDN contributors.
Your blueprint for a better internet.
background
Сокращённое CSS свойство background устанавливает сразу все свойства стиля фона, такие как цвет, изображение, источник и размер, или метод повтора.
Интерактивный пример
Исходный код этого интерактивного примера хранится в репозитории GitHub. Если вы хотите внести свой вклад в проект интерактивных примеров, пожалуйста клонируйте https://github.com/mdn/interactive-examples и отправьте нам запрос на извлечение..
Как и во всех сокращённых свойствах, любые пропущенные вложенные значения будут установлены в свои изначальные значения.
Синтаксис
/* Использование свойства */ background: green; /* Использование свойств и */ background: url("test.jpg") repeat-y; /* Использование и */ background: border-box red; /* Одно изображение, центрированное и масштабированное */ background: no-repeat center/80% url("../img/image.png");
Примечание: background-color можно определить только на последнем фоне, поскольку для всего элемента существует только один цвет фона.
Значения
Свойству можно указывать одно или более значений из данного списка в любом порядке:
Смотри background-size . Это свойство должно быть указано после , разделённого символом ‘/’.
Формальный синтаксис
background =
# (en-US) ? (en-US) ,=
|| (en-US)
[ (en-US) / ] (en-US) ? (en-US) || (en-US)
|| (en-US)
|| (en-US)
|| (en-US)
=
|| (en-US)
[ (en-US) / ] (en-US) ? (en-US) || (en-US)
|| (en-US)
|| (en-US)
|| (en-US)
|| (en-US)
=
| (en-US)
none=
[ (en-US) left | (en-US) center | (en-US) right | (en-US) top | (en-US) bottom | (en-US) ] (en-US) | (en-US)
[ (en-US) left | (en-US) center | (en-US) right | (en-US) ] (en-US) [ (en-US) top | (en-US) center | (en-US) bottom | (en-US) ] (en-US) | (en-US)
[ (en-US) center | (en-US) [ (en-US) left | (en-US) right ] (en-US) ? (en-US) ] (en-US) && (en-US) [ (en-US) center | (en-US) [ (en-US) top | (en-US) bottom ] (en-US) ? (en-US) ] (en-US)=
[ (en-US) | (en-US) auto ] (en-US) (en-US) | (en-US)
cover | (en-US)
contain=
repeat-x | (en-US)
repeat-y | (en-US)
[ (en-US) repeat | (en-US) space | (en-US) round | (en-US) no-repeat ] (en-US) (en-US)=
scroll | (en-US)
fixed | (en-US)
local=
content-box | (en-US)
padding-box | (en-US)
border-box=
| (en-US)
(en-US)=
| (en-US)=
| (en-US)
=
url( (en-US) * (en-US) ) | (en-US)=
src( (en-US) * (en-US) )Примеры
HTML
p class="topbanner"> Starry skybr /> Twinkle twinklebr /> Starry sky p> p class="warning">Here is a paragraphp> p>p>
CSS
.warning background: red; > .topbanner background: url("starsolid.gif") #00d repeat-y fixed; >Dark Background and Light Text — Firefox add-on
Modern Web is barely customizable. Most web designers try really hard to make their websites look the same for all users on all OSes and browsers and they try to eliminate any browser-specific behavior. This includes: font, font size, button placement guidelines (close button on the right or on the left, OK, Cancel buttons order and so on) and colors. We will concentrate on one problem: color customizability. People may want to override page colors for a variety of reasons: accessibility, preference to work in a dark room or just taste. But this is more complicated task rather than applying custom CSS with few overrides
Кастомизируемость современного веба оставляет желать лучшего. Большинство веб-дизайнеров стараются, чтобы их веб-сайты выглядели одинаково у всех пользователей независимо от их операционных систем, браузеров и, как следствие, их предпочтений. Но потребность в кастомизации есть. Например, не всегда стандартный размер шрифта подходит всем пользователям, да и сам шрифт не всегда выбирают как самый различимый. Также часто пользователи хотели бы видеть сайты в других цветах, часто в тёмных. Некоторые браузеры предоставляют возможность маштабирования страниц, а также игнорирования цветов, выставленных автором вебсайта, но часто это или слишком грубо (когда цвет текста несёт смысловую нагрузку, например, предупреждающая надпись на жёлтом фоне или программный код с подсвеченным синтаксисом), или этого недостаточно (есть ещё фоновые изображения). К счастью, уже все современные распространённые браузеры поддерживают расширения. Об одном таком, которое решает проблему изменения цветовой схемы страниц, и будет доклад, а также немного о смежных темах.
Краткое введение в то, что такое аддоны и что они могут делать
Аудитория, думаю, прекрасно с этим понятием знакома и не раз пользовалась, но на всякий случай. Аддоны — небольшие приложения на javascript для браузеров, которые могут незначительно встраиваться в UI браузеров (в виде кнопок, сайдбаров и хоткеев), а так же встраивать свой javascript и CSS в вебстраницы. Наиболее распространённый класс аддонов — блокировщики рекламы.
Зачем люди могут предпочитать тёмные темы
- Доступность. При некоторых патологиях зрения значительно проще воспринимать светлый текст на тёмном фоне.
- Удобство при работе в тёмной комнате (например, ночью). Поэтому часто такие темы называется ночным режимом (Night Mode).
- Личные вкусовые предпочтения.
Ограничения user CSS как общего решения для изменения цветов сайтов
- Узкоспециализированный CSS для конкретного вебсайта. Плюсы: при желании и упорстве можно сделать очень качественно. Минусы: при малейшем изменении на сайте стиль поломается; требуется создавать подобный стиль вручную для каждого сайта.
- Грубо перекрасить весь текст и фон в нужные цвета. Плюсы: просто и быстро (как с точки зрения разработки, так и с точки зрения производительности). Минусы: потеряется вся цветовая семантика текста (например, подсветка синтаксиса кода, выделенное жёлтым предупреждение, красным ошибка и т. д.); фоновые изображения можно или все оставить, или все убрать (см. ниже о проблеме).
- CSS filter: invert и аналоги. Плюсы: просто с точки зрения разработки; для средней светлой страницы результат будет максимально качественным. Минусы: производительность — даже прокрутка страницы начнёт заметно подтормаживать (Firefox for Android становится практически неюзабельным); изначально тёмные страницы станут светлыми, смешанные страницы останутся смешанными, только наоборот.
Решение на javascript, трудности с ним и их решения
- Обход и модификация стилей в `document.styleSheets`
- Изменение цвета на тёмный или светлый, сохранение тона (например, красный остаётся красным, но в зависимости от того, фон это или текст, становится тёмно-красным или светло-красным).
- Преобразование цвета в пространство HSL , замена канала L (Lightness).
- Преобразование цвета в пространство YPbPr, замена канала Y’.
- Градиенты в качестве фоновых изображений. Решение: парсинг значений и обработка цветов как фоновых как в пункте выше.
Ссылки
- https://addons.mozilla.org/firefox/addon/dark-background-light-text/
- https://github.com/m-khvoinitsky/dark-background-light-text-extension
Альтернативы, заслуживающие внимания
- https://addons.mozilla.org/firefox/addon/darkreader/
- https://addons.mozilla.org/firefox/addon/midnight-lizard-quantum/
Краткая история технического устройство аддонов для Firefox
- overlay add-on
- Установка\обновление только с перезагрузкой браузера
- Аддон имеет полный доступ к внутренним API браузера, никак не ограничен.
- Нет стабильного API — аддоны могут спонтанно ломаться при обновлении браузера.
- Первая попытка сделать аддоны безперезагрузочными
- Аддон начинается с файла bootstrap.js с функциями startup и shutdown, в которых разработчик должен сделать то, что хочет с браузером при помощи его DOM API .
- Все плюсы и минусы предыдущего типа, кроме необходимости перезагрузки браузера.
- Попытка сделать стабильный API для аддонов.
- всё ещё есть возможность (теперь опциональная) получить доступ к внутренним API браузера (которое не имеет гарантии стабильности)
- Стабильное API и невозможность выйти за его пределы (последнее — самый большой недостаток, который вызвал массу недовольств и даже сделал реализацию некоторых существующих аддонов невозможной)
- Причины появления:
- Необходимость закрыть внутренний API от аддонов, так как довольно сложно вносить изменения в браузер не ломая аддонов. Примеры крупных изменений, которые ломали аддоны: e10s (мультипроцессность), интеграция наработок из Servo.
- Трудности конкуренции с Chrome.
Abstract licensed under Creative Commons Attribution-ShareAlike 3.0 license