Reputation: 75
I have to write an extension for saving user credentials to my database server (like in LastPass). How can I catch submit action from authentication form on active tab to grab entered login and password for saving using my extension and show dialog to a user, if he wants to save credentials or not?
Upvotes: 4
Views: 6273
Reputation: 20665
Add a content script in your manifest and set it to run on some webpage:
"content_scripts": [{
"matches": ["http://*.example.com/*"],
"js": ["form_submits.js"],
"run_at": "document_start"
}]
Also add permissions:
"permissions": [
"tabs", "http://*.example.com/*"
],
In this content script listen to event "onsubmit" on forms, then contact with your extension using chrome.extension.sendRequest():
for (var i = 0; i < document.forms.length; i++) {
document.forms[i].addEventListener("submit", function(){
var form = this.form;
var data = [form.elements["user"], form.elements["password"]];
// contact with your background page and send the form data.
chrome.extension.sendRequest({'name':'form_submit', 'data':data}, function(){ /* callback from request */ }, false);
});
}
In your background script add listener to these calls:
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
switch (request.name) {
case 'form_submit':
var data = request.data;
// do something with your form credentials.
break;
}
});
****Edited.****
You could also execute JavaScript directly on current active Tab and add form submit listeners:
First get the current window and active tab:
chrome.windows.getCurrent(function callback)
chrome.tabs.getSelected(integer windowId, function callback)
http://code.google.com/chrome/extensions/windows.html#method-getCurrent
http://code.google.com/chrome/extensions/tabs.html#method-getSelected
Then execute JavaScript in it:
chrome.tabs.executeScript(integer tabId, object details, function callback)
http://code.google.com/chrome/extensions/tabs.html#method-executeScript
A comprehensive Google Chrome extensions API is here:
http://code.google.com/chrome/extensions/getstarted.html
Upvotes: 2