简体   繁体   English

运行Chrome扩展程序,并在页面加载时将数据提交到PHP脚本(自动执行该过程)

[英]Run chrome extension and submit data to PHP script on page load (automate the process)

I am first time using chrome extension for web crawling. 我是第一次使用chrome扩展程序进行网络爬网。 I get data in HTML popup and then submits it to PHP script on button click. 我在HTML弹出窗口中获取数据,然后单击按钮将其提交到PHP脚本。 Now I want to do this functionality on page load. 现在,我想在页面加载时执行此功能。 So on page load data will be collected and submit it to PHP script. 因此,页面加载数据将被收集并提交给PHP脚本。 I am using extension as below 我正在使用扩展名如下

menifest.json 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 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 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 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. 目前,我需要单击chrome扩展名,然后在popup.html中渲染数据,当我单击“提交”按钮时,数据将转到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). 编辑:单击扩展名(T符号)时,我添加了chrome扩展名的图像。 then it load information in popup. 然后在弹出窗口中加载信息。 When I click on submit data in popup goes to PHP script 当我单击弹出窗口中的提交数据时,转到PHP脚本

在此处输入图片说明

Use the background page 使用背景页面

In your manifest, change your current "background" key with: 在清单中,使用以下命令更改当前的"background"键:

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

and your "content_scripts" key with: 和您的"content_scripts"键,其中包含:

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

This will be background.html : 这将是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: 在您的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);
  }
});

Then your content.js will directly be: 然后,您的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);

Bonus: you don't need JQuery :) 奖励:您不需要JQuery :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM