开发者

Guarantee non-conflicness

I would like to make an addon to browser, that would show image of question mark if something was selected, and to show a tooltip with translation upon click on the image. Something like on nytimes web page when reading articles, but more user friendly. For showing the image I use this:

function ShowQuestionMark(e)                       
  {
  if (window.getSelection().toString() != "")
    { 
      /* add an img tag */
      document.onmouseup 开发者_开发问答= RemoveQuestionMark;
    }
  }

function RemoveQuestionMark(e)
{ 
  /* remove img tag */  
  document.onmouseup = ShowQuestionMark; 
}

document.onmouseup = ShowQuestionMark;

My goal is to make it work on every web page (or at as many as possible).

Now my first question. I assume, when I use it this way and load a page, which by default have a handler for onmouseup event, I override it and whatever was the handler, it won't be executed when firing onmouseup event. Am I correct?

Second question, how can I guarantee, that my script won't override/break any default behavior? Should I use binding? Or should I create new unique event? Or something entirely else?


I don't know the answer to your first question, because I've never directly assigned an event handler like that while writing an extension, knowing a conflict would occur. But I think the page's event handler would override yours. Either way, you need to avoid the conflict.

Anyway, here's how you avoid the conflict: use addEventListener():

function ShowQuestionMark(e) {
  if (window.getSelection().toString() != "") {
      document.removeEventListener("mouseup", ShowQuestionMark);
      /* add an img tag */
      yourImgTag.addEventListener("click", RemoveQuestionMark);
  }
}

function RemoveQuestionMark(e) {
  yourImgTag.removeEventListener("click", RemoveQuestionMark);
  /* remove img tag */  
  document.addEventListener("mouseup", ShowQuestionMark); 
}

document.addEventListener("mouseup", ShowQuestionMark);

Now, if the page is kind enough not to override or cancel the event (which it can still do), both your event handler and the page's event handler will be run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜