挑选:
所有这些方法都允许您(您的扩展程序)打开一个新窗口/对话框,并处理该页面的逻辑。此页面应与您的扩展程序一起打包。
请参阅消息传递以将输入的数据传递给您的扩展程序。
演示
扩展程序中的选项卡可以使用chrome.runtime.getBackgroundPage
. 我将在此演示中演示此功能,以及传统的消息传递方式:
manifest.json
{
"name": "Dialog tester",
"version": "1.0",
"manifest_version": 2,
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["open-dialog.js"]
}]
}
background.js
// Handle requests for passwords
chrome.runtime.onMessage.addListener(function(request) {
if (request.type === 'request_password') {
chrome.tabs.create({
url: chrome.extension.getURL('dialog.html'),
active: false
}, function(tab) {
// After the tab has been created, open a window to inject the tab
chrome.windows.create({
tabId: tab.id,
type: 'popup',
focused: true
// incognito, top, left, ...
});
});
}
});
function setPassword(password) {
// Do something, eg..:
console.log(password);
};
open-dialog.js
if (confirm('Open dialog for testing?'))
chrome.runtime.sendMessage({type:'request_password'});
dialog.html
<!DOCTYPE html><html><head><title>Dialog test</title></head><body>
<form>
<input id="pass" type="password">
<input type="submit" value="OK">
</form>
<script src="dialog.js"></script>
</body></html>
dialog.js
document.forms[0].onsubmit = function(e) {
e.preventDefault(); // Prevent submission
var password = document.getElementById('pass').value;
chrome.runtime.getBackgroundPage(function(bgWindow) {
bgWindow.setPassword(password);
window.close(); // Close dialog
});
};
使用方法的文档