I'm trying to implement message passing in my chrome extension.
It should pass a message from the popup script to the content script when a button in the popup has been clicked.
I can't get it to do anything (print to the console, alert, etc...) so I'm wondering if
a) I need to add message passing to the permissions in manifest. I haven't been able to find any info on this
b) I'm not specifying which tab to send to correctly
c) doing something else entirely different wrong that I haven't thought of
here's the code:
popup.js
document.getElementById("save-button").onclick = function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "new filter saved"}, function(response) {
console.log(response.farewell);
});
});
}
script.js
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 == "new filter saved") {
alert("message passed");
console.log("message passed");
walkWithFilter(); //method that I want to call
return true;
sendResponse({farewell: "goodbye"});
}
return false;
});
manifest.json
{
"manifest_version": 2,
"name": "filter",
"description": "This extension allows twitter users to filter content in their feed",
"version": "1.0",
"content_scripts":
[
{
"matches": ["*://*/*"],
"js": ["bower_components/jquery/dist/jquery.min.js", "script.js"],
"run_at": "document_end"
}
],
"permissions": [
"storage",
"contextMenus",
"background",
"https://twitter.com/",
"http://twitter.com/"
],
"icons": {
"16": "fa-moon.png"
},
"background": {
"scripts": ["background.js", "popup.js"]
},
"browser_action": {
"default_title": "filter",
"default_icon": "fa-moon.png",
"default_popup": "popup.html"
}
}
right now this is doing nothing -- no alert message pops up and nothing is printed to the console when I pressed the button with the click event.
EDIT --
I'm not sure if I should actually expect the alert to show up because I don't think javascript alerts work very well with popups, but I do think console statements should be working and they are not. If anyone has a better idea to test the functionality of the message passing - please let me know!
I think this should explain the functionality a little better:
1) User enters input into popup window 'save-button' and clicks save
2) onclick of the save-button, input is saved in localstorage (this part works)
3) onclick of the save-button, message is sent from popup.js to script.js telling it that new input has been saved to localstorage
4) Script.js receives message and prints to the regular console "message passed"
The reason I'm doing this is that I need to make the content script do some logic when it receives notice that new input has been saved in local storage. Does this seem reasonable?
Aucun commentaire:
Enregistrer un commentaire