diff js/background.js @ 10:ff5e5e3eba32

Implement feed subscription for web-based feed readers Add options page for configuring web-based feed readers which allow for subscribing to feeds via GET requests. Track tabs containing feed previews and inject a content script which retrieves the configured feed readers and keeps them in sync.
author Guido Berhoerster <guido+feed-preview@berhoerster.name>
date Fri, 07 Dec 2018 23:00:41 +0100
parents 5d7c13e998e9
children a4590add4901
line wrap: on
line diff
--- a/js/background.js	Tue Nov 27 16:05:14 2018 +0100
+++ b/js/background.js	Fri Dec 07 23:00:41 2018 +0100
@@ -17,6 +17,7 @@
     ...Object.values(feedParser.XMLNS)
 ];
 var tabsFeeds = new Map();
+var tabsFeedPreviews = new Map();
 var fetchingFeedPreview = fetch('web_resources/feed-preview.xhtml')
         .then(response => response.text());
 
@@ -38,7 +39,7 @@
     return contentType;
 }
 
-async function handleFeed(inputText, url) {
+async function handleFeed(inputText, tabId, url) {
     // fast-path: eliminate XML documents which cannot be Atom nor RSS feeds
     let inputTextStart = inputText.substring(0, 512);
     if (!FEED_MAGIC.some(element => inputTextStart.includes(element))) {
@@ -59,6 +60,9 @@
     }
     console.log(`parsed feed ${url}:\n`, feed);
 
+    // mark this feed preview for content script injection
+    tabsFeedPreviews.set(tabId, url);
+
     // render the preview document
     let feedPreviewDocument = new DOMParser()
             .parseFromString(await fetchingFeedPreview, 'text/html');
@@ -118,7 +122,7 @@
         inputText += decoder.decode(ev.data, {stream: true});
     });
     filter.addEventListener('stop', async ev => {
-        let result = await handleFeed(inputText, details.url);
+        let result = await handleFeed(inputText, details.tabId, details.url);
         filter.write(encoder.encode(result));
         filter.close();
     });
@@ -145,7 +149,7 @@
     }
 });
 
-browser.tabs.onUpdated.addListener((id, changeInfo, tab) => {
+browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
     if (typeof changeInfo.url === 'undefined') {
         // filter out updates which do not change the URL
         return;
@@ -153,9 +157,18 @@
 
     // 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.pageAction.hide(tabId);
+
+    // inject content script once if the requested URL is a feed preview
+    if (tabsFeedPreviews.get(tabId) === changeInfo.url) {
+        browser.tabs.executeScript(tabId, {
+            file: 'content_scripts/feed-readers.js'
+        });
+        tabsFeedPreviews.delete(tabId);
+    }
 });
 
 browser.tabs.onRemoved.addListener((tabId, removeInfo) => {
     tabsFeeds.delete(tabId);
+    tabsFeedPreviews.delete(tabId);
 });