如何让 Ajax 与 Bookmarklet 一起使用并绕过 Javascript 同源策略?
我正在尝试编写一个小书签,目标是能够将来自任何站点 X(单击小书签时所在的原始页面)的信息提交到我的站点服务器,同时停留在站点 X 上。
理想情况下,我能够发送回响应并让它在某个地方弹出,但这不是必需的。
我不断遇到同源策略的问题——从站点 X 开始,XMLHttpRequest 只能通过站点 X 的域启动。
有谁知道解决这个问题的方法(或者他们可以向我指出的教程)?一些带有书签的 Ajax?
非常感谢!
I am trying to write a Bookmarklet and the goal is to be able to submit information from any site X (the origin page they are on when clicking the bookmarklet) to my site's servers while staying on site X.
Ideally, I would be able to send a response back and have it pop up somewhere but this is not necessary.
I keep running into the issue of the same origin policy -- that from site X, XMLHttpRequests can only be initiated with site X's domain.
Does anyone know of a way around this (or a tutorial they can point me to)? some Ajax with a Bookmarklet?
Thanks so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 JSONP 执行跨域 ajax 请求(使用 GET 发送并以 JSON 形式接收数据)。
You can perform cross domain ajax request (send using GET and receive the data as JSON) using JSONP.
您加载的小书签可以将数据从主机页发布到您的服务器。这很奇怪,但只有 Javascript 受到同源策略的限制。
对另一台服务器进行
GET
或POST
调用工作正常。小书签可以在主页中注入隐藏的
IFRAME
,并带有src
属性,例如http://yourdomain.com/listen
。然后构建一个
FORM
,其属性:target
指向该IFRAME
。最后提交表单来
POST
数据。不幸的是,SOP 不会让您直接读取 POST 的响应,因为它发生在 IFRAME 中,并且具有除主机页之外的另一个域。
但是,如果您需要请求的反馈,您的书签可以使用
setInterval
每 X 毫秒轮询一次并使用 JSONP。调用类似以下内容:
http://yourdomain.com/get-post-status?id=2234234&callback=showResult
The bookmarklet that you load can POST data to your server from the host page. This is strange, but only Javascript is restricted by the Same Origin Policy.
Making
GET
orPOST
calls to another server work fine.The bookmarklet can inject a hidden
IFRAME
in the host page , with asrc
attribute likehttp://yourdomain.com/listen
.Then build a
FORM
with the attribute:target
pointing to thatIFRAME
.And finally submit the form to
POST
the data.The sad news, is SOP won't let you read the response of the POST directly, as it happens in the IFRAME and has another domain than the host page.
But if you need a feedback of the request, your bookmarklet can use
setInterval
to poll every X milliseconds and ask the status of the request, using JSONP.Calling something like:
http://yourdomain.com/get-post-status?id=2234234&callback=showResult