【问题标题】:Text selection and bubble overlay as Chrome extension文本选择和气泡覆盖作为 Chrome 扩展
【发布时间】:2012-07-21 04:58:20
【问题描述】:

我正在寻找一种方法来在 Chrome 中选择网站上的文本,并根据文本选择弹出带有内容的覆盖/工具提示。

以前有没有人这样做过或知道如何使工具栏弹出?

非常感谢。

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension jquery-tooltip


    【解决方案1】:

    您需要做的就是监听鼠标事件:

    • mousedown:隐藏气泡。
    • mouseup:显示气泡。

    例如,这可能会帮助您入门。需要进行更多调整,以确定您是否从向下->向上、向右->向左等(所有方向)启动了选择。您可以使用以下代码作为启动:

    contentscript.js

    // Add bubble to the top of the page.
    var bubbleDOM = document.createElement('div');
    bubbleDOM.setAttribute('class', 'selection_bubble');
    document.body.appendChild(bubbleDOM);
    
    // Lets listen to mouseup DOM events.
    document.addEventListener('mouseup', function (e) {
      var selection = window.getSelection().toString();
      if (selection.length > 0) {
        renderBubble(e.clientX, e.clientY, selection);
      }
    }, false);
    
    
    // Close the bubble when we click on the screen.
    document.addEventListener('mousedown', function (e) {
      bubbleDOM.style.visibility = 'hidden';
    }, false);
    
    // Move that bubble to the appropriate location.
    function renderBubble(mouseX, mouseY, selection) {
      bubbleDOM.innerHTML = selection;
      bubbleDOM.style.top = mouseY + 'px';
      bubbleDOM.style.left = mouseX + 'px';
      bubbleDOM.style.visibility = 'visible';
    }
    

    contentscript.css

    .selection_bubble {
      visibility: hidden;
      position: absolute;
      top: 0;
      left: 0;
      background:-webkit-gradient(linear, left top, left bottom, from(#2e88c4), to(#075698));
    }
    

    ma​​nifest.json

    将匹配部分更改为您要注入这些内容脚本的域。

    ...
    ...
      "content_scripts": [
        {
          "matches": ["http://*/*"],
          "css": ["main.css"],
          "js": ["main.js"],
          "run_at": "document_end",
          "all_frames": true
        }
    ...
    ...
    

    如果你想让它看起来像一个气泡,Nicolas Gallagher 为气泡做了一些很棒的 CSS3 demos

    【讨论】:

    • 您的 Chrome 扩展程序的答案非常棒,但被点赞的太少了。一旦我可以分配赏金(24 小时后),你就会得到它。非常感谢!
    • @BartKiers 啊,谢谢,没关系,我这样做是因为我喜欢尽我所能帮助别人!我通过使用 StackOverflow 和大量阅读文档来学习 :)
    • 我不知道如何将最后一个添加到 manifest.json 中...它说content_scripts 无效。
    • 把它放在博客或github等上。非常有帮助,谢谢。
    【解决方案2】:

    我写了一些类似于你所问的内容。我聆听用户选择文本,当有选择时,我显示了“Facebook 上的注释”、“定义”等内容的链接列表。

    在我开始写它的一两天后,我发现 google 将在未来的版本中添加上下文菜单支持,所以直到最近我才接触到这个(当我转换为上下文菜单时)。

    看一下代码:

    http://code.google.com/p/select-actions/source/browse/trunk/select_actions.js?r=4

    【讨论】:

    • 另外,我应该提到大多数人会立即卸载我的扩展程序,因为他们害怕内容脚本可以访问所有页面上的信息的安全消息。
    【解决方案3】:

    如果没有人提供更好的答案,那么您可能会看看 Google Dictionary 扩展是如何做到的(因为它的代码被最小化了,这会很困难)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 2019-07-24
      • 2013-05-15
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多