我想要做的是能够按下包含用户数据的特定页面上工具栏中的扩展按钮,按下它时刮取指定的数据,打开一个新窗口并加载URL,填写表单删除数据并提交表格。
到目前为止,我可以抓取数据并打开新窗口,但我需要一些帮助填写表单并提交。
的manifest.json
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test Extension"
},
"permissions": ["activeTab"]
}
content.js
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.text && (msg.text == "report_back")) {
var userdata = [];
userdata[0] = document.getElementsByClassName("firstname").innerText;
userdata[1] = document.getElementsByClassName("surname").innerText;
userdata[3] = document.getElementsByClassName("dob").innerText;
sendResponse(credentials);
}
});
background.js
function domData(element) {
alert("DOM content:\n" + element); // debug whats been sent
chrome.windows.create({incognito: true, url: "http://admin.mysite.com/newuser.php"});
}
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.sendMessage(tab.id, { text: "report_back" },
domData);
});
样品刮-page.html中
<span class="firstname">John</span>
<span class="surname">Doe</span>
<span class="dob">1st June 1990</span>
newuser.php
<form action="newuser.php">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="surname"><br>
Last name: <input type="text" name="dob"><br>
<input type="submit" value="Submit">
</form>
答案 0 :(得分:0)
这是一个具有activeTab
权限的原始未经测试的解决方案,它不会在任何地方注入内容脚本,但仅在按下工具栏按钮时才使用programmatic code injection:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
code: "(" + (function() {
["firstname", "surname", "dob"].map(function(c) {
return document.getElementsByClassName(c).innerText;
}).join("\n");
}).toString() + ")()"
}, function(result){
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
return;
}
chrome.windows.create({incognito: true, focused: true,
url: "http://admin.mysite.com/newuser.php"}, function(window) {
chrome.tabs.executeScript({
code: "(" + (function(data) {
var data = data.split("\n");
["firstname", "surname", "dob"].forEach(function(c, i) {
document.querySelector("input[name='"+c+"']").value = data[i];
});
document.forms[0].submit();
}).toString() + ")(" + result[0] + ")"
}
});
});
});
另一种更好看的解决方案是使用file:
参数而不是code:
注入单独的内容脚本文件并使用消息传递。