David Small David Small - 6 months ago 9
HTML Question

How can I ask the user if they'd like to save their username/password like Chrome?

I'm making a chrome extension that will act as a password manager similar to Chrome's but with some different functionality.

When the user submits the log in form, my extension is able to intercept the submit and grab the username and password. Now I'd like to display a pop-up asking the user if they'd like to save the password or not.

If it's possible to display my own custom HTML on top of whatever page exists, it would disappear since the page is reloading. So should I store the data in a session variable and each time the page loads, check if it has something?

I'd like to avoid just opening up another window, it looks sloppy. Is there a better way to grab the form data and use if after the page has been loaded after the submit?

Answer

This can be done using a combination of event and content scripts.

Register content script with manifest.json

"content_scripts": [ {
  "js": [ "/util/jquery.js", "main.js"],
  "matches": [ "http://*/*", "https://*/*"],
  "run_at": "document_start",    
}],

The content script listens for a form to be submitted

$("form").submit(function(e) {
  var $this = $(this);
  console.log('submit');
  var formData = findFormData($this); //function searches form for username/password

  //Send message to background page with user/pass data
  chrome.runtime.sendMessage({greeting:'form_submit', data:formData}, function(){ /*if needed */ });

});

Create register the background script with the manifest (use persistent=false to make the background script an "event" script). We'll also need the following permissions

"background": {
  "scripts": ["/background/background.js"],
  "persistent" : false
},
"permissions": [
  "activeTab",
  "storage",
  "webNavigation"
]

Finally, we add the message listener into the background page

chrome.runtime.onMessage.addListener(function(request, sender,     sendResponse) {
switch (request.greeting) {
  case 'form_submit':
    var data = request.data;
    console.log('We Have Data!', request.data);

    //We want to display the prompt when this page loads, so add listener
    chrome.webNavigation.onCompleted.addListener( function askUser(details) {

      //Create prompt here!

      //remove the onCompleted listener so it doesn't appear when navigating again
      chrome.webNavigation.onCompleted.removeListener(askUser);
    });

    sendResponse({farewell: "success"});

    break;
  }
});