From 4cddd8497c31ff5cdcf2b6914c5968f32941c9b8 Mon Sep 17 00:00:00 2001 From: Aad Versteden Date: Thu, 31 Dec 2020 10:36:57 +0100 Subject: [PATCH 1/2] Use URL interface in apply-css example By using the URL interface, the user is ascertained that the piece of code does not manipulate the DOM. Keeping them in the right mental context for the example. The apply-css example uses the protocol of the URL of the tab to determine if a pageAction should be shown. Any page that is hosted over http or https will receive the page action. The former implementation creates an anchor tag, assigns the URL to that, and fetches the protocol from there. This PR alters that to using the URL interface. This makes it clear to the user that we're staying in JavaScript land and will not start manipulating the visible DOM. I would argue this is cleaner all together, but I'm very open to learning about a different opinion. The URL interface is more broadly supported than the pageAction.setIcon which this example is also dependent on, so this change should not change compatibility of this Browser Extension. --- apply-css/background.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/apply-css/background.js b/apply-css/background.js index 3c0b1aad..039a6974 100644 --- a/apply-css/background.js +++ b/apply-css/background.js @@ -29,9 +29,8 @@ function toggleCSS(tab) { Returns true only if the URL's protocol is in APPLICABLE_PROTOCOLS. */ function protocolIsApplicable(url) { - var anchor = document.createElement('a'); - anchor.href = url; - return APPLICABLE_PROTOCOLS.includes(anchor.protocol); + const protocol = (new URL(url)).protocol; + return APPLICABLE_PROTOCOLS.includes(protocol); } /* From b1b896627a31dd4e365d59bbb8afb77f93e25afb Mon Sep 17 00:00:00 2001 From: Aad Versteden Date: Thu, 31 Dec 2020 13:28:25 +0100 Subject: [PATCH 2/2] Add doc that received url parameter must be a valid URL The `new URL(url)` statement will throw an error if the supplied string is not a valid URL. Adding a note to the function to clarify that as requested by @Rob--W. --- apply-css/background.js | 1 + 1 file changed, 1 insertion(+) diff --git a/apply-css/background.js b/apply-css/background.js index 039a6974..8846b0b1 100644 --- a/apply-css/background.js +++ b/apply-css/background.js @@ -27,6 +27,7 @@ function toggleCSS(tab) { /* Returns true only if the URL's protocol is in APPLICABLE_PROTOCOLS. +Argument url must be a valid URL string. */ function protocolIsApplicable(url) { const protocol = (new URL(url)).protocol;