PlaidWeb / webmention.js

Client-side library for rendering webmentions from webmention.io
MIT License
111 stars 15 forks source link

Handle www redirects? #46

Open j2kun opened 1 month ago

j2kun commented 1 month ago

Hi there,

I have a www and non-www version of my page. Due to some DNS changes, my website changed from its official URL being jeremykun.com to www.jeremykun.com, and old webmentions are not queried correctly by this JS plugin, even though they resolve to the same page. Would it be feasible to add an option to dynamically allow removing or adding www. to the domain? I would do this via add-urls, but it would be more straightforward to update the JS directly.

j2kun commented 1 month ago

FYI, this diff sufficed for me to get it to work for my website. Happy to send it as a PR if it seems OK

diff --git a/static/webmention.js b/static/webmention.js
index 1eab9cb..773c140 100644
--- a/static/webmention.js
+++ b/static/webmention.js
@@ -77,6 +77,11 @@ Allowed parameters:
         (replies/mentions/etc.) as being part of the reactions
         (favorites/bookmarks/etc.) instead of in a separate comment list.

+    query-www-redirects:
+
+        If set to true, query for both `www.` and non-`www.` versions of the
+        page URL. Defaults to false.
+
 A more detailed example:

 <!-- If you want to translate the UI -->
@@ -128,6 +133,7 @@ A more detailed example:
   const sortDir = getCfg("sort-dir", "up");
   /** @type {boolean} */
   const commentsAreReactions = getCfg("comments-are-reactions", false);
+  const queryWwwRedirects = getCfg("query-www-redirects", false);

   /**
    * @typedef MentionType
@@ -262,6 +268,16 @@ A more detailed example:
     return url.substr(url.indexOf('//'));
   }

+  /**
+   * Modify a URL by removing www.
+   *
+   * @param {string} url The URL to remove www. from
+   * @returns {string}
+   */
+  function stripwww(url) {
+    return url.replace('www.', '');
+  }
+
   /**
    * Deduplicate multiple mentions from the same source URL.
    *
@@ -398,6 +414,13 @@ A more detailed example:
         pages.push(stripurl(url));
       });
     }
+    if (queryWwwRedirects) {
+        pages.forEach(function (url) {
+            if (url.indexOf('www.') > 0) {
+                pages.push(stripwww(url));
+            }
+        });
+    }

     let apiURL = `https://webmention.io/api/mentions.jf2?per-page=${maxWebmentions}&sort-by=${sortBy}&sort-dir=${sortDir}`;