如何使用 Chrome API 复制链接以突出显示

Zuh*_*aha 6 javascript google-chrome-extension

在Chrome浏览器中,我们可以选择一个文本,然后上下文菜单(右键)有一个选项复制链接以突出显示

可以使用chrome 扩展中的chrome API复制链接或应用/删除选择范围上的特定突出显示。

const selection = window.getSelection();
const range = selection.getRangeAt(0);
// chrome.highlight.add(range);
// chrome.highight.remove();
Run Code Online (Sandbox Code Playgroud)

Ler*_*ang 6

我想提供一种解决方法:复制此文件(或我测试过的文件)并将其作为内容脚本或后台脚本之一放入您的扩展中,您只需通过传递选择来获取结果即可使用它如下:

  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}`;
    }
  
Run Code Online (Sandbox Code Playgroud)

}

你可以这样使用它:

var userSelection = window.getSelection();
var derective_url = this.getLinkToSelected(userSelection)
Run Code Online (Sandbox Code Playgroud)

我认为将其做成 API 会很容易。当我可以自己做时,我会更新这个答案。


小智 3

我认为你不能使用 Chrome API 来做到这一点。但您可以自己编写链接。

当您查看链接突出显示 URL 的结构时。

/sf/ask/5026467561/#:~:text=How%20to%20copy%20link%20to%20highlight

它由三部分组成:

  1. 原始网址
  2. 参数#:~:text=
  3. 以及实际的 URL 编码文本选择
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const linkToHighlight = location.href + "#:~:text=" + encodeURIComponent(range.toString())
Run Code Online (Sandbox Code Playgroud)