I am pretty new to writing userscripts for Chrome/Firefox. I was trying to get the AJAX generated JSON data from a website and send them to my own server, to analyze them and put them into a database.
I managed to send the data with Ajax and put them into a text file on my own server. But in the Chrome Console it says that I have:
Uncaught SyntaxError: Unexpected token j
, but I already have got each message, that 'Data were sent' and that I'm 'After the call' -those are the logging messages.
Is there a callback, that I should implement, or am I missing something obvious? I am putting a shortened version of my code up here.
// Injecting javascript in the original page
function inject(func) {
var source = func.toString();
var script = document.createElement('script');
script.innerHTML = "(" + source + ")()";
document.body.appendChild(script);
}
function injection() {
}
// This function intercepts the ajax
function interceptAjax() {
$('body').ajaxSuccess (
function (event, requestData, settings) {
serverData = requestData.responseText;
if(JSON.parse(settings.data).method == "dashboard.getPaginatedPlextsV2"){
console.log("Sending");
$.ajax({
type: "POST",
url: "http://mywebsite.com/collectdata.php",
data: { json: JSON.stringify(serverData) },
success: function(msg) {
console.log("Data were sent");
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("Failed: " + xhr.status + " - " + thrownError);
}
});
console.log("After the call");
}
}
);
}
// A helperfunction for the ajaxInterception to work in Chrome
function addJS_Node (text, s_URL, funcToRun) {
var D = document;
var scriptNode = D.createElement('script');
scriptNode.type = "text/javascript";
if(text) scriptNode.textContent = text;
if(s_URL) scriptNode.src = s_URL;
if(funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
targ.appendChild(scriptNode);
}
// This function is necessary to intercept the ajax
addJS_Node(null, null, interceptAjax);
inject(injection);
Couple things:
Is mywebsite.com
the same domain as the target page? If not, then you can't do cross-domain AJAX like that (unless the target-page server has a generous CORS policy).
If so, then you control the server (or have access), so why mess about with a userscript for the data? ;-)
This line:
if(JSON.parse(settings.data).method == "dashboard.getPaginatedPlextsV2")
looks prone to cause errors.
Even if you are reasonably sure that all of the page's AJAX calls send only valid JSON data, not all of the data will have a method
property. (EG: it looks like the AJAX call to http://mywebsite.com/collectdata.php
might not have one.
You need to make that check a little more crash-resistant. Something like this (untested):
var jsonData = null;
try {
jsonData = JSON.parse (settings.data);
}
catch (e) {
jsonData = null;
}
if (jsonData && jsonData.method
&& jsonData.method == "dashboard.getPaginatedPlextsV2"
) {
...