Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Обработка событий в расширениях Firefox

Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.

Gecko использует события (events) для передачи информации о происходящем во время работы браузера тем модулям, которые желают знать об этом.  События подразделяются на несколько различных категорий. Данная статья поможет Вам узнать основную информацию об этом и даст ссылки на более подробную документацию, описывающую каждую из категорий. Также в этой статье описаны несколько случаев, предоставляющих особый интерес.

Типы событий

Существует множесто типов событий, которые могут использовать авторы приложений и расширений для получения оповещений от элементов браузера (browser) и закладок (tabbrowser) об изменениях, связанных с загруженным в них содержимым.

Простые DOM-события

Для обработки простого DOM-события используйте такой код:

function callback(evt) {
  // Здесь Ваш код. Проверяйте значение evt.target чтобы обрабатывать только нужные события.
}

b.addEventListener("event", callback, false)

В приведенном примере b - это браузер (browser) или закладка (tabbrowser), от которой Вы хотите получать события. Имейте в виду, что события могут приходить от любого фрейма внутри браузера или в случае закладки - от нескольких браузеров с такой закладкой.

Ниже пречислены наиболее интересные DOM-события:

Событие Описание
DOMLinkAdded Генерируется, когда в документе обнаружена новая ссылка (HTML элемент <link>).
DOMTitleChanged Генерируется, когда изменен заголовок страницы.
DOMContentLoaded Генерируется, когда инициализация DOM полностью завершена.
load  Генерируется, когда страница, включая картинки, была полностью загружена.
unload Генерируется, когда пользователь закрыл страницу.
pageshow Генерируется, когда страница показана вновь.
pagehide Генерируется, когда страница скрыта.

Более детально о событиях load, unload, pageshow and pagehide, а также о других событиях читайте в статье Firefox's caching behaviour.

Обработчики процесса загрузки

Для отображения дополнительной информации о ходе загрузки данных из веба можно использовать обработчики процесса загрузки. Они предоставляют детальную информацию о ходе загрузки данных из веба. И браузер (browser) и закладка (tabbrowser) поддерживают следующие конструкции:

var progressListener = {
  // add nsIWebProgressImplementation here
}

b.addProgressListener(progressListener);

Where b is the browser or tabbrowser you want to listen to events for. There are code snippets available that give more detail on using web progress listeners.

For a tabbrowser, the above code will only get events from the browser that is currently displayed at the time the event occurs. In order to listen to events from all browsers, including those not currently being displayed, the following example can be used:

var tabsProgressListener = {
  // add tabs progress listener implementation here
}

gBrowser.addTabsProgressListener(tabsProgressListener);

This lets you receive events related to all tabs. More information about listening to events from all tabs is available.

How events are used by Firefox

The Firefox frontend already listens for a number of these progress events from web pages. Most of this goes on in browser.js.

DOMLinkHandler

The DOMLinkHandler object is called by the DOMLinkAdded event in order to detect any RSS feeds, site icons, or OpenSearch plugins for the web site.

pageShowEventHandlers

The pageShowEventHandlers() function is called by the pageshow event and is used to populate the character set menu and update the UI elements associated with any detected feeds or OpenSearch plugins for the website.

XULBrowserWindow

XULBrowserWindow is an nsIWebProgressListener used to get progress events for the currently visible browser. It is used to update the UI for many different reasons:

  • Update the progress bar and status messages as pages load
  • Turn on and off the throbber as pages load
  • Set the site icon when available
  • Update the address bar as the user navigates
  • Hide notification bars when appropriate as the user navigates
  • Apply the site zoom preferences to newly loading pages
  • Update the bookmarking star button UI
  • Update the identity display as the site's security changes

TabsProgressListener

This object is a tabs progress listener and receives events for all browsers in the window. It is used to detect when a webpage attempts to refresh itself and allow the user to block the attempt.

How events are used by the tabbrowser

tabbrowser maintains a set of objects relating to progress listening for each browser. First it creates a browser-status-filter and adds it as a web progress listener for the browser. Next it creates an internal object to receive all web progress events from the browser. This is created by the method mTabProgressListener(). This receives events from the browser-status-filter. The filter acts to reduce the number of status and progress events to improve performance. The filters are held in the array mFilters, the internal listeners in the array mTabListeners.

The internal listeners are used to send out progress events to listeners registered with addProgressListener() (which receives events from the browser that is currently visible) and addTabsProgressListener() (which receives events from all browsers).

See also

 

Метки документа и участники

 Внесли вклад в эту страницу: rcyber
 Обновлялась последний раз: rcyber,