Mercurial > addons > firefox-addons > feed-preview
diff background.js @ 0:bc5cc170163c
Initial revision
author | Guido Berhoerster <guido+feed-preview@berhoerster.name> |
---|---|
date | Wed, 03 Oct 2018 23:40:57 +0200 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/background.js Wed Oct 03 23:40:57 2018 +0200 @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2018 Guido Berhoerster <guido+feed-preview@berhoerster.name> + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +'use strict'; + +var tabsFeeds = new Map(); + +// until content handlers become available to webextensions +// (https://bugzilla.mozilla.org/show_bug.cgi?id=1457500) intercept all +// responses and change the content type from application/atom+xml or +// application/rss+xml to application/xml which will then be handled by a +// content script +browser.webRequest.onHeadersReceived.addListener(details => { + if (details.statusCode != 200 || + typeof details.responseHeaders === 'undefined') { + return; + } + + let contentTypeHeader = details.responseHeaders.find(element => { + return element.name.toLowerCase() === 'content-type'; + }); + if (typeof contentTypeHeader !== 'undefined') { + let contentType = contentTypeHeader.value.split(';'); + let mediaType = contentType[0].trim().toLowerCase(); + if (mediaType === 'application/atom+xml' || + mediaType === 'application/rss+xml') { + contentType[0] = 'application/xml'; + contentTypeHeader.value = contentType.join(';'); + } + } + + return {responseHeaders: details.responseHeaders}; +}, {urls: ['http://*/*', 'https://*/*'], types: ['main_frame']}, +['blocking', 'responseHeaders']); + +browser.runtime.onMessage.addListener((request, sender, sendResponse) => { + let tab = sender.tab; + if (typeof tab !== 'undefined') { + // content script sending feeds + tabsFeeds.set(tab.id, request); + browser.pageAction.show(tab.id); + } else { + let response = tabsFeeds.get(request); + // popup querying feeds + sendResponse(tabsFeeds.get(request)); + } +}); + +browser.tabs.onUpdated.addListener((id, changeInfo, tab) => { + if (typeof changeInfo.url === 'undefined') { + // filter out updates which do not change the URL + return; + } + + // hide the page action when the URL changes since it is no longer valid, + // it will be shown again if the content script detects a feed + browser.pageAction.hide(tab.id); +}); + +browser.tabs.onRemoved.addListener((tabId, removeInfo) => { + tabsFeeds.delete(tabId); +});