I know message passing is used for the purpose but somehow it is not working on onClick event of my background page. I am getting following exception:
Error in event handler for (unknown): TypeError: Cannot read property 'data' of undefined
at chrome-extension://aimjdbbnlgjodealdppjdpligkbjbmmb/background.js:27:31
at disconnectListener (extensions::messaging:338:9)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Event.dispatchToListener (extensions::event_bindings:386:22)
at Event.dispatch_ (extensions::event_bindings:371:27)
at Event.dispatch (extensions::event_bindings:392:17)
at dispatchOnDisconnect (extensions::messaging:293:27)
Code given below:
manifest.json
{
"manifest_version": 2,
"name" : "My Ext",
"description" : "XXX",
"version" : "1.0",
"permissions": [
"tabs"
],
"content_scripts" : [{
"matches" : ["http://example.com/"],
"js" : ["jquery.js","script.js"]
}],
"background":{
"scripts": ["jquery.js","background.js"]
},
"browser_action": {
"default_title": "XX"
}
}
dashboard.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="jquery.js"></script>
<script src="background.js"></script>
</head>
<body>
<form>
<textarea id="search"></textarea>
<input id="button" type="button" value="Search" />
</form>
</body>
</html>
Script.js
var currentURL = document.location.href;
$(document).ready(function(){
$("#button").click(function()
{
alert( "Handler for .click() called." );
});
});
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse)
{
alert(msg);
if (msg.method == "getHTML")
sendResponse({data: "Welcome from Content Script"});
});
background.js
$(document).ready(function()
{
chrome.browserAction.onClicked.addListener(function(activeTab){
var loaderURL = chrome.extension.getURL("dashboard.html");
_tab = activeTab;
chrome.tabs.create({ url: loaderURL });
});
$("#button").click(function()
{
chrome.extension.sendMessage({method: "getHTML",param:"myParam"}, function(response)
{
alert(response.data);
});
});
});
I can't use chrome.tabs.sendMessage because onClick event I am unable to find tab Id