代码之家  ›  专栏  ›  技术社区  ›  Zuhair Taha

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

  •  0
  • Zuhair Taha  · 技术社区  · 4 年前

    在Chrome浏览器中,我们可以选择一个文本,然后在上下文菜单(右键单击)中有一个选项 Copy link to highlight

    可以以及如何使用复制链接或应用/删除选择范围上的特定突出显示 chrome API 镀铬加长件。

    const selection = window.getSelection();
    const range = selection.getRangeAt(0);
    // chrome.highlight.add(range);
    // chrome.highight.remove();
    
    0 回复  |  直到 4 年前
        1
  •  5
  •   Lerner Zhang    4 年前

    我想提供一个变通方法:复制 this file (或 this one 我已经测试过),并将其作为内容脚本或背景脚本之一放在扩展中,您只需通过传递选择来使用它,即可获得如下结果:

      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是很容易的。当我能自己做的时候,我会更新这个答案。

        2
  •  1
  •   Moritz Rieger    4 年前

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

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

    https://stackoverflow.com/questions/71806679/how-to-copy-link-to-highlight-using-chrome-api#:~:text=How%20to%20copy%20link%20to%20highlight

    它由三部分组成:

    1. 原始URL
    2. 这个 #:~:text= 参数
    3. 和实际的URL编码文本选择
    const selection = window.getSelection();
    const range = selection.getRangeAt(0);
    const linkToHighlight = location.href + "#:~:text=" + encodeURIComponent(range.toString())