在Chrome浏览器中,我们可以选择一个文本,然后右键菜单(右键)有一个选项复制链接以突出显示
可以使用 chrome 扩展中的 chrome API 复制链接或应用/删除选择范围上的特定突出显示。
const selection = window.getSelection();
const range = selection.getRangeAt(0);
// chrome.highlight.add(range);
// chrome.highight.remove();
我想提供一种解决方法:复制这个文件(或这个我已经测试过)并将其作为内容脚本或后台脚本之一放置在您的扩展中,您只需通过传递选择来使用它得到结果如下:
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}`;
}
}你可以这样使用它:
var userSelection = window.getSelection();
var derective_url = this.getLinkToSelected(userSelection)
我认为将其做成 API 会很容易。当我可以自己做时,我会更新这个答案。
当您查看链接突出显示 URL 的结构时。
https://stackoverflow.com/questions/71806679/how-to-copy-link-to-highlight-using-chrome-api#:~:text=How%20to%20copy%20link%20to%20highlight
它由三部分组成:
#:~:text=
参数
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const linkToHighlight = location.href + "#:~:text=" + encodeURIComponent(range.toString())