2016-11-07 68 views
-3

如何通過單擊browserAction按鈕來關閉Chrome擴展實例?如何防止我的代碼每次點擊按鈕時運行的次數越來越多?

我正在使用Chrome擴展,我想通過點擊browserAction按鈕來激活擴展,當我再次單擊它時,我想關閉該擴展的實際實例,以便我可以再次啓動它再次點擊browserAction圖標。

https://gist.github.com/p10shinde/fb24e5c01d435d138a9bcfdb5b1734aa

添加的jquery.js

background.js

var actvTabId; 
var toggle = false; 


chrome.browserAction.onClicked.addListener(function(tab) 
{ 

ws = new WebSocket("ws://127.0.0.1:1234/"); 

toggle = !toggle; 

    chrome.tabs.getSelected(null, function(tab) 
    { 
       actvTabId = tab.id 

      if(toggle) 
      { 
       chrome.browserAction.setBadgeBackgroundColor({ tabId : actvTabId,color: "green" }); 
       chrome.browserAction.setBadgeText({tabId : actvTabId,text: 'R'}); 

        chrome.tabs.query({active:true}, function(tabs) 
        { 
         for(var i=0;i<tabs.length;i++) 
         { 
          if(tabs[i].selected == true) 
          { 
           //sending to active tab (myscript) from back 
           try 
           { 
           //send to active tab to myscript from backgrund 
           chrome.tabs.sendMessage(tabs[i].id, {from : 'btn_record2',msg : 'dontremove'}, function(response) {}); 
           alert('sent'); 
           } 
           catch(e){} 
          } 
         } 
        }); 


       chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) 
       { 
        if (request.from =='btn_record_myscript') 
        { 
         if(typeof(request) != 'undefined') 
         { 
          var msg = {cmd : request.command,trgt : request.target , val : request.value}; 
          //sending to java desktop app (can comment) 
          //ws.send(JSON.stringify(msg)); 
          alert('sent to java'); 
         } 
        } 
       }); 
      } 
      else 
      { 
      ws.close(); 
      chrome.browserAction.setBadgeBackgroundColor({tabId : actvTabId, color: "red" }); 
      chrome.browserAction.setBadgeText({tabId : actvTabId,text: ''}); 
      } 






     ws.onopen = function opn() { 

      console.log('Connection Successfull.'); 

     }; 

     ws.onmessage = function (evt) { 

      console.log("From Server : "+evt.data); 
     }; 

     ws.onclose = function() { 
      // alert("Closed!"); 
      console.log('closed'); 
      ws.close(); 
     }; 

     ws.onerror = function(err) { 
      //alert("Error: " + err); 
      console.log('Connection Failed. Check if server is up and running.'); 
     }; 

    }); 

}); 

myScript.js

var typed = ''; 
var events = []; 

     chrome.extension.onMessage.addListener(function (message,sender, sendResponse) 
     { 
      if(message.from === 'btn_record2') 
      { 
       alert('gotchaa'); 
       if(message.msg == 'remove') 
       { 
        alert("1"); 
        monitorEvents({'main' : document, 'actn':'rem'}); 
        alert('removed'); 
       } 
       else if(message.msg == 'dontremove') 
       { 
        alert("2"); 
        monitorEvents({'main' : document, 'actn':'add'}); 
        alert('added'); 
       } 

      } 

       function monitorEvents(element) 
       { 
        //handler 
        var log = function(e) 
        { 
         if(typeof(e.toElement) != 'undefined') 
         { 
          if(e.type == 'click' || e.type == 'change') 
          { 
           console.log(e); 
           var ele = document.getElementsByTagName(e.target.nodeName); 
           var target_lcl = createXPathFromElement(ele[0]); 

           chrome.runtime.sendMessage({from : 'btn_record_myscript',command : e.type,target:target_lcl,value:''}); 

             if(typeof(e.toElement.href) != 'undefined') 
             monitorEvents(document); 
           } 
         } 
         else 
         { 
         if(e.type == 'change') 
         console.log(e); 

         var ele = document.getElementsByTagName(e.target.nodeName); 
         var target_lcl = createXPathFromElement(ele[0]); 
         typed = e.target.value; 
         chrome.runtime.sendMessage({from : 'btn_record_myscript', command : 'type' , target : target_lcl , value : typed}); 
         } 

        } 


         for(var i in element.main) 
         { 
         if(i.startsWith("on")) 
          events.push(i.substr(2)); 
         } 

         events.forEach(function(eventName) 
         { 
          if(element.actn == 'add') 
          { 
           element.main.addEventListener(eventName, log,false); 
          } 
          else if(element.actn == 'rem') 
          { 
           element.main.removeEventListener(eventName, log,false); 
          } 
         }); 
       } 
     }); 


     ////new xpath element (is being used) 
     //dont bother about this function 
     function createXPathFromElement(elm) 
     { 
      var allNodes = document.getElementsByTagName('*'); 
      for (var segs = []; elm && elm.nodeType == 1; elm = elm.parentNode) 
      { 
       if (elm.hasAttribute('id')) { 
         var uniqueIdCount = 0; 
         for (var n=0;n < allNodes.length;n++) { 
          if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++; 
          if (uniqueIdCount > 1) break; 
         }; 
         if (uniqueIdCount == 1) { 
          segs.unshift('id("' + elm.getAttribute('id') + '")'); 
          return segs.join('/'); 
         } else { 
          segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]'); 
         } 
       } else if (elm.hasAttribute('class')) { 
        segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]'); 
       } else { 
        for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) { 
         if (sib.localName == elm.localName) i++; }; 
         segs.unshift(elm.localName.toLowerCase() + '[' + i + ']'); 
       }; 
      }; 
      return segs.length ? '/' + segs.join('/') : null; 
     }; 

的manifest.json

{ 
"name": "WindowFetchDOMExtension", 
"version": "1.0.0", 
"manifest_version": 2, 
"description" : "This extension fetches the DOM of current page.", 
"icons": { "48": "bear.png"}, 

"browser_action": { 
    "default_icon": { "16": "bear.png", "32": "bear.png" }, 
    "default_title": "WindowFetch DOM" 
}, 
"permissions": ["tabs"], 
"background": { 
    "scripts": ["background.js"] 
}, 
"content_scripts": [{ 
    "matches": ["http://*/*", "https://*/*"], 
    "js": ["jquery.js","myScript.js"] 
}] 
} 

新增信息描述從OP評論的問題:
這是一個分機。當我打開它時,它會捕獲點擊事件。當我再次點擊browserAction圖標時,它應該停止監聽點擊事件。現在這裏是問題:當我再次點擊啓動時,它會爲該事件監聽兩次。如果我把它關掉再打開,那麼它會聽4次單擊事件。

+0

「close」是什麼意思?擴展程序在「激活」時會執行什麼操作?你是否想用另一個擴展來控制擴展? – Xan

+0

沒有。它的單個擴展。當我打開它時,它會捕獲點擊事件。當我再次點擊browserAction圖標時,它應該停止監聽點擊事件。 現在,這裏是問題,當我再次點擊開始時,它會爲該事件監聽兩次,如果我將其關閉並再次打開,那麼它將聽一次單擊事件4次。希望問題很明確... –

+1

問題很明顯,「我的代碼中存在一個錯誤」,而不是「如何做一些模糊的事情」。你應該包括相關的代碼,然後我們可以提供幫助。 – Xan

回答

1

insted的下面,

chrome.extension.onMessage.addListener(function (message,sender, sendResponse) 
    { 
     if(message.from === 'btn_record2') 
     {...} 
    }); 

我已經使用chrome.extension.onMessage.addListener(dostuff);和裏面

function dostuff(message,sender, sendResponse) 
     { 
     chrome.extension.onMessage.removeListener(dostuff); 
     //rest code below 
     } 

刪除以前的聽衆,它解決了我的問題。

避免使用匿名函數。

相關問題