Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

javascript - Text selection and bubble overlay as Chrome extension

I am looking for a way to select text on a website in Chrome and have a overlay/tooltip pop with content depending on the text selection.

Has anyone done this before or knows from the top of their heads how to make the toolip pop-up?

Much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All you need to do is listen for mouse events:

  • mousedown: to hide the bubble.
  • mouseup: to show the bubble.

For example, this might help you get started. More tweaks are needed, to figure out if you initiated the selection from down->up, right->left, etc (all directions). You can use the following code as a startup:

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));
}

manifest.json

Change the matches portion to the domain you want to inject these content scripts.

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

If you want to style it to look like a bubble, Nicolas Gallagher did some awesome CSS3 demos for bubbles!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...