3

I am trying to accomplish this login process.

In the extension, there is popup.html, popup.js, background.js and content.js as usual.

In popup.html, there are username and password inputfields and login button.

My vision is: I will catch both inputs in popup.js and send them to background.js and from there, i will send them to django backend. django backend returns logged-in token.

firstly, is this possible way?

my first step is not working: i cannot send message from popup.js to background.js. no error in console, also no success. this is my code:

popup.js

handleLoginClick_: function(){
  var email = this.email.value;
  var pwd = this.pwd.value; 
  chrome.tabs.sendMessage(tab.id, {asking: "login"}, function(response) {
    sendToDjango(response.answer);
  });
}

background.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { 
  if (request.asking === "login"){
    console.log('got msg from popup.js');
    return;
  } 
});

what am I doing wrong?

this is the manifest.json:

{
"name" : "myBIZMark",
"version" : "1.1",
"description" : "collect competing company's keywords",
"permissions": [
  "tabs", "contextMenus", "<all_urls>", "storage"
],
"browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
},  
"background": {
  "persistent": false,
  "scripts": ["jquery111.js","background.js"]
},
"manifest_version": 2,
"content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["jquery111.js", "contentscript.js","popup.js"]
  }
]
}
doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

2

Your message in popup.js is targeted toward the content scripts, not the background page. You need to use chrome.runtime, not chrome.tabs.

Replace:

chrome.tabs.sendMessage(tab.id, {asking: "login"}, function(response) {
  sendToDjango(response.answer);
});

With:

chrome.runtime.sendMessage({asking: "login"}, function(response) {
  sendToDjango(response.answer);
});

In summary:

chrome.tabs.sendMessage = background -> content

chrome.runtime.sendMessage = content -> background

anderspitman
  • 9,230
  • 10
  • 40
  • 61
  • hey Anders, sorry, but it is not working. in my case, i have ``popup.js``->``background.js``, not content->background. any other solutions? :( – doniyor Aug 05 '14 at 07:50
  • It would be good to figure out what the problem was, if you have a little extra time. According to your manifest popup.js is a content page so what I said *should* work. Two things: 1. Are you aware that the background page doesn't print to the same console as the content scripts and web pages? You access the background page console by going to your extensions page and clicking under "Inspect views: background page". 2. If you're making a popup, chances are you'll run into styling issues eventually. See [this question](http://stackoverflow.com/q/12783217/943814). Note my answer for details – anderspitman Aug 05 '14 at 18:03