In the Chrome browser, we can select a text, then the context menu (right click) there is an option Copy link to highlight
It is possible and how to copy link or apply/remove that specific highlight on a selection range using chrome API at chrome extensions.
const selection = window.getSelection();
const range = selection.getRangeAt(0);
// chrome.highlight.add(range);
// chrome.highight.remove();
In the Chrome browser, we can select a text, then the context menu (right click) there is an option Copy link to highlight
It is possible and how to copy link or apply/remove that specific highlight on a selection range using chrome API at chrome extensions.
const selection = window.getSelection();
const range = selection.getRangeAt(0);
// chrome.highlight.add(range);
// chrome.highight.remove();
Share
Improve this question
edited Apr 9, 2022 at 9:17
Zuhair Taha
asked Apr 9, 2022 at 9:11
Zuhair TahaZuhair Taha
3,0522 gold badges38 silver badges37 bronze badges
1
- 1 Hi, were you able to solve this, and how? I am trying to do the same. – Tejas Commented Aug 19, 2023 at 20:37
2 Answers
Reset to default 6I'd like to provide a workaround: copy this file(or this one I have tested) and place it in your extension as one of your content scripts or background scripts, and you just use that by passing a selection to get the results as follows:
getLinkToSelected(selection) {
const result = generateFragment(selection);
let url = `${location.origin}${location.pathname}${location.search}`;
if (result.status === 0) {
const fragment = result.fragment;
const prefix = fragment.prefix ?
`${encodeURIComponent(fragment.prefix)}-,` :
'';
const suffix = fragment.suffix ?
`,-${encodeURIComponent(fragment.suffix)}` :
'';
const textStart = encodeURIComponent(fragment.textStart);
const textEnd = fragment.textEnd ?
`,${encodeURIComponent(fragment.textEnd)}` :
'';
console.log(`prefix: ${prefix}\ntextstart: ${textStart}\ntextend: ${textEnd}\nsuffix: ${suffix}`)
url = `${url}#:~:text=${prefix}${textStart}${textEnd}${suffix}`;
console.log(`fragment url: ${url}`)
return url;
} else {
return `Could not create URL ${result.status}`;
}
}
You can use it like this:
var userSelection = window.getSelection();
var derective_url = this.getLinkToSelected(userSelection)
I think it would be easy to make it an API. When I can do it myself, I will update this answer.
I don't think you can do this with the Chrome API. But you can pose the link yourself.
When you look at the structure of the link-to-highlight URL.
https://stackoverflow./questions/71806679/how-to-copy-link-to-highlight-using-chrome-api#:~:text=How%20to%20copy%20link%20to%20highlight
It consist of three parts:
- the original URL
- the
#:~:text=
parameter - and the actual URL encoded text selection
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const linkToHighlight = location.href + "#:~:text=" + encodeURIComponent(range.toString())