Chrome: 有道词典取词插件的实现

风行水上 @ 2014-01-22 12:38:56
标签:

    有道词典有一个Chrome的鼠标划线取词插件。机缘碰巧,想到了要看一下其插件源代码实现。

    Content Script

    监听用户鼠标事件,"选词动作"发生后向Background Page发送查询请求。

    chrome.extension.sendRequest({action:"word", msg: word.text, offset: word.pos}, onText);
    

    Background Page

    后台页面监听到查词请求后,向有道词典主程序发送HTTP请求进行查询。

      var url = 'http://127.0.0.1:50000/word='+word+'&offset='+offset+'&';
      url += 'src=' + browserName + '&';
      var xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.send();
    

    后台页面还回定时(每2分钟)向词典主程序发送heartbeat信号(特定的GET请求参数)。

    补遗

    该插件用了两种机制以确保查询事件的发生:

    1. 由用户鼠标事件触发查询
    2. 后台页面定时发送请求以触发查询事件

    Chrome API 使用

    监听页面请求

    chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
     ...
    });
    

    发送页面请求

    chrome.extension.sendRequest({action:"word", msg: word.text, offset: word.pos}, onText);
    

    读取文件内容

    本质上是一个AJAX操作,URL通过chrome.extension.getURL()函数获得。

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(data) {
              if (xhr.readyState == 4) {
       	    var text = xhr.responseText;    // 读取到的文件内容
              }
        }
        var url = chrome.extension.getURL("flg.txt") +'#'+ new Date().getTime();
        xhr.open('GET', url, true);
        xhr.send();    
    
    
    标签:

      分享到:
      comments powered by Disqus

      26/29ms