从 PageMod ContentScriptFile 发出 Ajax 请求
我正在 beta 构建器中构建它,但我真的不知道如何在我的 contentScriptFile 中进行 ajax 调用。我想拉一个ajax请求来动态地将数据拉回到脚本中,这样我就可以改变页面内容。我一直在搜索,显然是错误的术语。感谢帮助!感谢
main.js
代码:
exports.main = function() {};
var data = require("self").data;
var pageMod = require("page-mod");
pageMod.PageMod({
include: "http://www.mozilla.org/*",
contentScriptWhen: 'ready',
contentScriptFile: [
data.url('jquery.1.7.1.js'),
data.url('common.js'),
data.url("mozilla.top.js")
]
})
mozilla.top.js
代码:
var qs = parseQS();
var foo= qs['string'];
var Request = require('request').Request;
Request({
url: "http://www.myremotepage.org?q="+foo,
onComplete: function (response) {
alert(response);
}
}).get();
alert('test');
旧代码阐明了最终目标 - http 请求不会返回任何内容,即使它在浏览器中工作。假设这是第 3 方 ajax 工具的权限问题,并使用附加请求工具从上面开始。
代码:
/*
$.ajax({
url: 'http://www.myremotepage.org?q='+foo,
data: {q:strSearchQuery},
dataType: 'json',
success: function(data) {
var div = $("<div style='background-color: #ececec;'><h2 style='text-align: right; font-size: 11px; color: #666;'>Test</h2><ul id='ptcid'></ul></div>");
alert(data.length);
for(var i = 0; i < data.length; ++i)
{
alert('test');
div.find('ul').append('<li></li>');
div.find('ul li:last').append('<h3>' + data[i].header+ '</h3>');
div.find('ul li:last').append('<div>'+data[i].body+'</div>');
div.find('ul li:last').append('<div>' + data[i].footer + '</div>');
}
div.insertBefore('#header');
}
});
*/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您面临的一个直接问题是 mozilla.top.js 作为内容脚本添加,并尝试使用 Request 模块。您不能在内容脚本中使用诸如 request 之类的 SDK 模块,您需要在 main.js 中发出请求,然后使用worker.port.emit() 将请求数据传递到您的内容脚本中。这些文档详细介绍了有关内容脚本通信的一些详细信息:
https://addons.mozilla.org/en-US/developers/docs/sdk/1.4/dev-guide/addon-development/content-scripts/using-port.html
示例实现如下所示:
在您的内容脚本中:您将向“got-request”事件附加一个侦听器:
这是使用此代码的构建器的工作示例 - 它非常非常简单,但希望会有所帮助:
https://builder.addons.mozilla.org/addon/1034982/latest/
One immediate problem you have is that mozilla.top.js is added as a content script, and tries to use the Request module. You cannot use SDK modules such as request in a content script, you need to instead make the request in main.js and then deliver the request data into your content script by using worker.port.emit(). The docs go into some detail about content script communications:
https://addons.mozilla.org/en-US/developers/docs/sdk/1.4/dev-guide/addon-development/content-scripts/using-port.html
A sample implementation would look like:
In your content script: you would attach a listener to the 'got-request' event:
Here's a working example on builder that uses this code - it's very very simple but hopefully will help:
https://builder.addons.mozilla.org/addon/1034982/latest/