通过Bookmarklet发送文本跨域

时间:2010-02-03 20:58:04

标签: javascript cross-domain bookmarklet cross-site

我需要用户导航到某个特定页面,该页面上有一个充满有用文本的div。然后单击我的书签并将该div中的文本发送回我的服务器,该服务器与当前域不同。我已经成功地在书签上点击jQuery并选择了文本。现在我需要找出一种方法将该文本跨域发送到我的服务器。我用jQuery尝试了JSONP,我的文本对于url来说太长了。我的第二个想法是打开一个新窗口并从我的域加载一个页面,然后以某种方式将所选文本插入到新窗口中,之后用户可以单击提交并将该数据发送到我的服务器。这不适用于javascript跨站点原因。任何人都有这方面的经验或想法吗?感谢。

3 个答案:

答案 0 :(得分:4)

生成一个表单(使用DOM)并POST数据(您可能希望以iframe为目标,但它会被点燃并忘记)。

答案 1 :(得分:3)

以下是将文本发布到远程服务器的示例。 如果你想改变你有iframe的页面,你可以在远程服务器上打印javascript来说出成功的话。或者一个弹出窗口说完了。在远程服务器上,您可以打印它以进行弹出:

<script> parent.document.getElementById('postmessage').style.display='block'; parent.alert('Successfully posted');</script>

在您要通过制作表单和iframe发送信息的网页上。

<span id="postmessage" style="display:none">Success Message</span>
<form action="http://www.remoteserver.com/upload_test.php" method="post" target="post_to_iframe">
  <input type="hidden" value="the text to send to remote server" />
  <input type="submit" value="Submit" />
</form>

<!-- When you submit the form it will submit to this iFrame without refreshing the page and it will make the popup and display the message. -->
<iframe name="post_to_iframe" style="width: 600px; height: 500px;"></iframe>

答案 2 :(得分:2)

使用javascript创建iframe。然后将表单添加到iframe并提交。提交表单后,将触发onload回调。

var i=document.createElement('iframe');
i.setAttribute('name', 'frame-id');
i.setAttribute('id', 'frame-id');
i.setAttribute('allowtransparency', 'true');
i.setAttribute('style', 'border: 0; width: 1px; height: 1px; position: absolute; left: 0; top: 0;');
i.setAttribute('onload', 'iframeFormSubmitted();');

document.body.appendChild(i);

var html = '<html><body>' +
'<form action="/post_url" method="post" id="iframe-form" accept-charset="utf-8">' +
'<input type="hidden" name="id" value="' + your_text + '"/>' +
'</form>' +
'<scr'+"ipt>var e=encodeURIComponent,w=window,d=document,f=d.getElementById('f');" +
"d.getElementById('iframe-form').submit();" +
'</scr'+"ipt></body></html>";

window.frames['frame-id'].document.write(html);