Skip to content

Commit

Permalink
Improve handling of target="_blank" links
Browse files Browse the repository at this point in the history
  • Loading branch information
david-tejada committed May 5, 2022
1 parent b9814e3 commit c4d95df
Show file tree
Hide file tree
Showing 3 changed files with 211 additions and 0 deletions.
186 changes: 186 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
}
},
"dependencies": {
"parse-domain": "^7.0.0",
"tippy.js": "^6.3.7",
"webextension-polyfill": "^0.8.0"
},
Expand Down
24 changes: 24 additions & 0 deletions src/content/click-element.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import browser from "webextension-polyfill";
import { parseDomain, ParseResultType, fromUrl } from "parse-domain";
import { focusesOnclick } from "../lib/dom-utils";
import { applyEmphasisStyles, applyInitialStyles } from "../lib/styles";
import { intersectors } from "./intersectors";
Expand All @@ -21,10 +22,19 @@ export async function clickElement(
}, 300);
(target.element as HTMLInputElement).focus();
} else {
// Sometimes websites use links with target="_blank" but don't open a new tab.
// They probably prevent the default behavior with javascript. For example Slack
// has this for opening a thread in the side panel. So here we make sure that
// if the main domains are equal just do a normal click and let the page handle it
const linkMainDomain = getMainDomain(
(target.element as HTMLLinkElement).href
);
const locationMainDomain = getMainDomain(window.location.href);
if (
target.element.tagName === "A" &&
(newTab ||
(target.element.getAttribute("target") === "_blank" &&
linkMainDomain !== locationMainDomain &&
(target.element as HTMLLinkElement).href &&
(target.element as HTMLLinkElement).href !== location.href))
) {
Expand All @@ -50,3 +60,17 @@ export async function clickElement(
}
}
}

function getMainDomain(url: string): string | undefined {
const parseResult = parseDomain(fromUrl(url));

// Check if the domain is listed in the public suffix list
if (parseResult.type === ParseResultType.Listed) {
const { domain, topLevelDomains } = parseResult;

const topLevel = topLevelDomains.join(".");
return `${domain!}.${topLevel}`;
}

return undefined;
}

0 comments on commit c4d95df

Please sign in to comment.