Browse Source

Trigger polyfill for page-local links

Chromium’s implementation currently does not trigger when clicking links
pointing to quotes within the same page. As a workaround, listen to link
clicks, and activate the polyfill when a link points to a fragment within
the same page.
tags/v0.1.0-src
Gerben 3 years ago
parent
commit
2d4d2afb5c
2 changed files with 28 additions and 3 deletions
  1. +1
    -1
      demo.html
  2. +27
    -2
      src/polyfill.ts

+ 1
- 1
demo.html View File

@@ -59,7 +59,7 @@
const message = (fragmentDirective
? fragmentDirective._implementation === 'text-fragments-ts'
? 'Yes'
: 'No <em>(your browser appears to support text fragments already!)</em>'
: 'Partially <em>(your browser appears to support text fragments already! But it might not work when clicking links that point to fragments within this same page, so the polyfill is invoked when clicking the links below)</em>'
: 'No <em>(something went wrong?)</em>'
);
usingPolyfill.innerHTML = message;


+ 27
- 2
src/polyfill.ts View File

@@ -69,10 +69,35 @@ function highlightRanges(ranges: Range[]): void {
}
}

// Listen to link clicks, and activate the polyfill when a link points to a fragment within the same page.
function addLinkClickListeners() {
const linkElements = [
...document.getElementsByTagName('a'),
...document.getElementsByTagName('area'),
]
linkElements.forEach(element => {
element.addEventListener('click', () => {
if (element.href.split('#')[0] === document.URL.split('#')[0]) {
const fragId = element.href.split('#')[1];
if (fragId && fragId.includes(':~:')) {
const fragmentDirective = fragId.substring(fragId.indexOf(':~:') + 3);
applyFragmentDirective({
document,
documentFragmentDirective: fragmentDirective,
});
}
}
});
});
}

function install(): void {
// Do nothing if the browser already supports (text) fragment directives.
if (browserSupportsTextFragments())
if (browserSupportsTextFragments()) {
// Chromium’s implementation currently does not trigger when clicking links pointing to quotes within the same page. Use this as a workaround (listening to hashchange won’t help, as we cannot access the fragment directive).
addLinkClickListeners();

return;
}

pretendBrowserSupportsTextFragments();



Loading…
Cancel
Save