这可以使用事件和内容脚本的组合来完成。
使用 manifest.json 注册内容脚本
"content_scripts": [ {
"js": [ "/util/jquery.js", "main.js"],
"matches": [ "http://*/*", "https://*/*"],
"run_at": "document_start",
}],
内容脚本侦听要提交的表单
$("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 */ });
});
使用清单创建注册后台脚本(使用 persistent=false 使后台脚本成为“事件”脚本)。我们还需要以下权限
"background": {
"scripts": ["/background/background.js"],
"persistent" : false
},
"permissions": [
"activeTab",
"storage",
"webNavigation"
]
最后,我们将消息监听器添加到后台页面中
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;
}
});