[英]Run chrome extension and submit data to PHP script on page load (automate the process)
我是第一次使用chrome擴展程序進行網絡爬網。 我在HTML彈出窗口中獲取數據,然后單擊按鈕將其提交到PHP腳本。 現在,我想在頁面加載時執行此功能。 因此,頁面加載數據將被收集並提交給PHP腳本。 我正在使用擴展名如下
menifest.json
{
"manifest_version": 2,
"name": "Test Extension",
"version": "1.0",
"offline_enabled": true,
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": [ "http://*/*", "https://*/*"],
"js": ["jquery.min.js","content.js"],
"run_at": "document_end"
}],
"permissions": [
"tabs",
"http://*/*",
"file:///*",
"downloads"
],
"page_action": {
"default_title": "Test Extension",
"default_popup": "popup.html"
}
}
content.js
chrome.runtime.onMessage.addListener(function(msg, sender, response) {
/* First, validate the message's structure */
if (msg.from && (msg.from === "popup")
&& msg.subject && (msg.subject === "DOMInfo")) {
/* Collect the necessary data
* (For your specific requirements `document.querySelectorAll(...)`
* should be equivalent to jquery's `$(...)`)*/
var domInfo = {
name : $('ul.companyDetails li:nth-child(1) > br').get(0).nextSibling.nodeValue.trim(),
address : $('ul.companyDetails li:nth-child(2) > br').get(0).nextSibling.nodeValue.trim() + " "
+ $('ul.companyDetails li:nth-child(2) > br').get(1).nextSibling.nodeValue.trim(),
reg_date : $('ul.companyDetails li:nth-child(3) > br').get(0).nextSibling.nodeValue.trim(),
legal_form : $('ul.companyDetails li:nth-child(4) > br').get(0).nextSibling.nodeValue.trim()
};
/* Directly respond to the sender (popup),
* through the specified callback */
response(domInfo);
}
});
popup.js
/* Update the relevant fields with the new data */
function setDOMInfo(info) {
document.getElementById("name").value = info.name;
document.getElementById("address").value = info.address;
document.getElementById("reg_date").value = info.reg_date;
document.getElementById("legal_form").value = info.legal_form;
}
/* Once the DOM is ready... */
window.addEventListener("DOMContentLoaded", function() {
//console.log("DOMContented...")
/* ...query for the active tab... */
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
/* ...and send a request for the DOM info... */
chrome.tabs.sendMessage(
tabs[0].id,
{ from: "popup", subject: "DOMInfo" },
/* ...also specifying a callback to be called
* from the receiving end (content script) */
setDOMInfo);
});
});
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('btn_php_call')
.addEventListener('click', download);
});
function download()
{
event.preventDefault();
// The URL to POST our data to
var postUrl = 'link to PHP script';
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed by URLEncoding each field's contents
// Handle request state change events
xhr.onreadystatechange = function() {
};
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Send the request and set status
xhr.send($('#frm_info').serialize());
}
popup.html
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<form id="frm_info">
<h3 style="font-weight:bold; text-align:center;"> DOM Info </h3>
<input type="text" name="name" id="name" value="">
<input type="text" name="address" id="address" value="">
<input type="text" name="reg_date" id="reg_date" value="">
<input type="text" name="legal_form" id="legal_form" value="">
<input type="button" id="btn_php_call" value="submit">
</form>
</body>
</html>
目前,我需要單擊chrome擴展名,然后在popup.html中渲染數據,當我單擊“提交”按鈕時,數據將轉到PHP。 我想在頁面加載時執行此操作,因此用戶無需手動執行。
編輯:單擊擴展名(T符號)時,我添加了chrome擴展名的圖像。 然后在彈出窗口中加載信息。 當我單擊彈出窗口中的提交數據時,轉到PHP腳本
使用背景頁面
在清單中,使用以下命令更改當前的"background"
鍵:
"background": { "page" : "background.html", "persistent": true}
和您的"content_scripts"
鍵,其中包含:
"content_scripts": [{"matches":"the_URLs_you_want_to_scrape", "js" : ["content.js"], "run_at": "document_idle"}]
這將是background.html :
<html>
<body>
<form id=myForm>
<input type="text" name="name" id="name">
<input type="text" name="address" id="address">
<input type="text" name="reg_date" id="reg_date">
<input type="text" name="legal_form" id="legal_form">
</form>
<script src="background.js"></script>
</body>
</html>
在您的background.js文件中包括以下內容:
chrome.runtime.onMessage.addListener(function(message){
if (message.from == "cs") {
document.getElementById("name").value = message.name;
document.getElementById("address").value = message.address;
document.getElementById("reg_date").value = message.reg_date;
document.getElementById("legal_form").value = message.legal_form;
var encodedData = [].reduce.call(document.getElementById("myForm").elements, function(acc,cur){
acc.push(cur.name+"="+encodeURIComponent(cur.value));return acc},[]).join("&");
var xhr = new XMLHttpRequest();
xhr.onload = function(){
//check the response
}
xhr.open("POST",your_link_to_PHP_script);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(encodedData);
}
});
然后,您的content.js將直接為:
var myMessage = {
from: "cs",
name : document.querySelector('ul.companyDetails li:nth-child(1) > br').nextSibling.nodeValue.trim(),
address : document.querySelector('ul.companyDetails li:nth-child(2) > br').nextSibling.nodeValue.trim() + " "
+ document.querySelectorAll('ul.companyDetails li:nth-child(2) > br')[1].nextSibling.nodeValue.trim(),
reg_date : document.querySelector('ul.companyDetails li:nth-child(3) > br').nextSibling.nodeValue.trim(),
legal_form : document.querySelector('ul.companyDetails li:nth-child(4) > br').nextSibling.nodeValue.trim()
};
chrome.runtime.sendMessage(myMessage);
獎勵:您不需要JQuery :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.