每次单击按钮时,如何防止我的代码运行的次数增加?

时间:2016-11-07 15:10:03

标签: javascript google-chrome-extension

如何通过点击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次。

1 个答案:

答案 0 :(得分:1)

在下面提到,

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
        }

删除以前的侦听器,它解决了我的问题。

避免使用匿名函数。