簡體   English   中英

使用潤滑脂monkey解析JSONP響應(來自express.js服務器)客戶端

[英]parse JSONP response (from express.js server) clientside using greasemonkey

我們正在研究油脂單據腳本,以從快遞服務器跨域提取數據。 (我們在這里找到了適用於普通html網站的代碼:)

你可以讓它為油猴工作嗎? (也許與unsafeWindow嗎?)

app.js:

var express = require("express");
var app = express();
var fs=require('fs');
  var stringforfirefox = 'hi buddy!'



// in the express app for crossDomainServer.com
app.get('/getJSONPResponse', function(req, res) {

    res.writeHead(200, {'Content-Type': 'application/javascript'});
    res.end("__parseJSONPResponse(" + JSON.stringify( stringforfirefox) + ");");
});
app.listen(8001)

油脂:

// ==UserScript==
// @name          greasemonkeytestscript
// @namespace     http://www.example.com/
// @description   jQuery test script
// @include       *
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js

// ==/UserScript==


function __parseJSONPResponse(data) {    alert(data); }       // ??????????

document.onkeypress = function keypressed(e){

    if (e.keyCode == 112) {
        var script = document.createElement('script');
        script.src = 'http://localhost:8001/getJSONPResponse';
        document.body.appendChild(script); // triggers a GET request
        alert(script);



    }
}

我以前從未使用過Express ,但是該應用似乎正在返回如下代碼:

__parseJSONPResponse("\"hi buddy!\"");

放置在target-page scope中的<script>節點中。

這意味着Greasemonkey腳本還必須將__parseJSONPResponse函數放置在目標頁面范圍內。

一種方法是:

unsafeWindow.__parseJSONPResponse = function (data) {
    alert (data);
}


但是,您似乎控制了Express應用程序。 如果是這樣,那么不要使用JSONP進行此類操作。 使用GM_xmlhttpRequest()

app.js可能會變成:

var express             = require ("express");
var app                 = express ();
var fs                  = require ('fs');
var stringforfirefox    = 'hi buddy!'

app.get ('/getJSONPResponse', function (req, res) {

    res.send (JSON.stringify (stringforfirefox) );
} );

app.listen (8001)


GM腳本如下所示:

// ==UserScript==
// @name        greasemonkeytestscript
// @namespace   http://www.example.com/
// @description jQuery test script
// @include     *
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant       GM_xmlhttpRequest
// ==/UserScript==

document.onkeypress = function keypressed (e){

    if (e.keyCode == 112) {
        GM_xmlhttpRequest ( {
            method:     'GET',
            url:        'http://localhost:8001/getJSONPResponse',
            onload:     function (respDetails) {
                            alert (respDetails.responseText);
                        }
        } );
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM