运行chrome扩展并在页面加载时将数据提交给PHP脚本(自动执行该过程) [英] Run chrome extension and submit data to PHP script on page load (automate the process)

查看:97
本文介绍了运行chrome扩展并在页面加载时将数据提交给PHP脚本(自动执行该过程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用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:// / *,
下载
],

page_action:{
default_title:测试扩展,
default_popup :popup.html
}
}

content.js



  chrome.runtime.onMessage.addListener(函数(msg,sender,response){

/ * First ,验证消息的结构* /
if (msg.from&& (msg.from ===popup)
&& msg.subject&& (msg.subject ===DOMInfo)){
/ *收集必要的数据
*(根据您的具体要求,document.querySelectorAll(...)`
*应该是等价于jquery的`$(...)`)* /


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)。 (1).nextSibling.nodeValue.trim(),$ b() $ b 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()
};
/ *通过指定的回调* /
响应(domInfo)直接响应发件人(弹出)
*;
}
});



popup.js

  / *用新数据更新相关字段* / 
函数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;

$ b / *一旦DOM准备就绪... * /
window.addEventListener(DOMContentLoaded,function(){
//console.log (DOMContented ...)
/ * ...查询活动选项卡... * /
chrome.tabs.query({
active:true,
currentWindow:true
},函数(标签){
/ * ...并发送DOM信息的请求... * /
chrome.tabs.sendMessage(
标签[0] .id,
{from:popup,主题:DOMInfo},
/ * ...还指定从接收端调用
*的回调(内容脚本)* /
setDOMInfo);
});
});

document.addEventListener('DOMContentLoaded',function(){
document.getElementById('btn_php_call')
.addEventListener('click',download);
});

函数下载()
{
event.preventDefault();

//将数据发布到
的URL postUrl ='链接到PHP脚本';

//设置异步AJAX POST请求
var xhr = new XMLHttpRequest();
xhr.open('POST',postUrl,true);

//准备要由URLEncoding每个字段的内容发布的数据



//处理请求状态更改事件
xhr。 onreadystatechange = function(){

};
xhr.setRequestHeader('Content-Type','application / x-www-form-urlencoded');
//发送请求并设置状态
xhr.send($('#frm_info')。serialize());
}

popup.html

 < html> 
< head>
< script type =text / javascriptsrc =jquery.min.js>< / script>
< script type =text / javascriptsrc =popup.js>< / script>
< / head>
< body>
< form id =frm_info>
< h3 style =font-weight:bold; text-align:center;> DOM Info< / h3>
< input type =textname =nameid =namevalue =>
< input type =textname =addressid =addressvalue =>
< input type =textname =reg_dateid =reg_datevalue =>
< input type =textname =legal_formid =legal_formvalue =>
< input type =buttonid =btn_php_callvalue =submit>
< / form>
< / body>

< / html>

目前我需要点击Chrome扩展,然后在popup.html中进行数据渲染,当我点击提交按钮,然后数据发送到PHP。我想在页面加载时做到这一点,所以用户不需要手动进行。

编辑:
当我点击扩展名(T符号)时,我添加了Chrome扩展的图片。那么它会弹出加载信息。当我点击提交数据弹出去PHP脚本





在您的清单中,更改当前的background键:

background:{page:background.html ,persistent:true}



和您的content_scripts


$ b

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 =textname =nameid =name>
< input type =textname =addressid =address>
< input type =textname =reg_dateid =reg_date>
< input type =textname =legal_formid =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(){
//检查响应
}
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:)

I am first time using chrome extension for web crawling. I get data in HTML popup and then submits it to PHP script on button click. Now I want to do this functionality on page load. So on page load data will be collected and submit it to PHP script. I am using extension as below

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>

Currently I need to click on chrome extension then data renders in popup.html and when I click on submit button then data goes to PHP. I want to do it on page load so user will no need to do it manually.

Edit : I added image of chrome extension when I click on extension (T symbol). then it load information in popup. When I click on submit data in popup goes to PHP script

解决方案

Use the background page

In your manifest, change your current "background" key with:

"background": { "page" : "background.html", "persistent": true}

and your "content_scripts" key with:

"content_scripts": [{"matches":"the_URLs_you_want_to_scrape", "js" : ["content.js"], "run_at": "document_idle"}]

This will be 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>

In your background.js file include this:

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);
  }
});

Then your content.js will directly be:

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);

Bonus: you don't need JQuery :)

这篇关于运行chrome扩展并在页面加载时将数据提交给PHP脚本(自动执行该过程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆