我们正在开发一个greasemonkeyscript来从跨域的express服务器中提取数据。 (我们发现适用于普通 html 站点的代码 here : )
你能让这个为greatmonkey工作吗? (也许使用 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)
greasemonkey脚本:
// ==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!\"");
它被放入 <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);
}
} );
}
}
关于javascript - 使用greasemonkey 解析客户端的JSONP 响应(来自express.js 服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180049/