3

我想获得一个成功注入的内容脚本,以向注入的基于AngularJS的Chrome扩展发送消息。将消息从内容脚本传递到基于Angular JS的Chrome扩展

注入控制器方法是这样的:

$scope.selectElement = function() { 
    // Close the extension window 
    window.close(); 

    window.chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
     console.log(sender.tab ? 
        "from a content script:" + sender.tab.url : 
        "from the extension"); 
     if (request.greeting == "hello") 
     sendResponse({farewell: "goodbye"}); 
    } 
); 

    // Send content script to web page 
    window.chrome.tabs.executeScript(null, { file: 'app/bower_components/jquery/jquery.js' }, function() { 
    window.chrome.tabs.executeScript(null, { file: 'app/scripts/libs/dom_selector.js' }); 
    }); 
}; 

注入脚本调用一旦网页被点击以下:

$(document).click(function(event) { 
    console.log($(event.target)); 
    chrome.runtime.sendMessage({greeting: "hello"}, function(response) { 
    console.log(response); 
    }); 
}); 

这火(出现在控制台的第一个日志消息) ,但第二条日志消息仅打印undefined

我想也许window.close()可能是问题,但window.chrome.tabs.executeScript调用工作正常,所以我不知道为什么事件监听器不会触发。它在错误的地方吗?我有一种感觉,因为我应该只是在某个地方宣布它,对吧?如果它在像这样的控制器中,每次运行该方法时都会设置,然后每个侦听器都会响应一个事件,导致事件响应被多次发送。它是否正确?

对此有何AngularJS指导,深受欢迎...

回答

2

这是打破了它的window.close()。令人讨厌的是,因为我需要关闭弹出窗口,所以用户可以在屏幕上选择任何HTML元素。但我可以证实,删除该行允许我得到来自听众的回应。

相关问题