制作一个POST当前URL的javascript书签

时间:2017-07-15 02:56:30

标签: javascript html post bookmarklet

我试图制作一个javascript书签,将当前网址发布到我的API。例如,类似于Instapaper bookmarklet所做的事情。我编写了以下脚本,通过一个minifier传递它并将其作为href添加到我用作按钮的<a>标记中。我希望能够将此标记拖到书签栏。

javascript: (function() {
  var url = document.location.href
  var uri = "http://localhost:3001/api/v1/links/bookmarklet?url=" + url + "&id=1"

  xhr = new XMLHttpRequest();
  xhr.open("POST", encodeURI(uri));

  xhr.send();
}());

目前我只是在localhost:3001的本地服务器上测试它,并在localhost:3000上运行我的应用程序。如果我在我的应用程序上按下按钮(在localhost:3000上)它确实发出了帖子请求,但它将脚本本身添加到当前网址顶部的地址栏。

http://localhost:3000/!function()%7Bvar%20e=%22http://localhost:3001/api/v1/links/bookmarklet?url=%22+document.location.href+%22&id=1%22;xhr=new%20XMLHttpRequest,xhr.open(%22POST%22,encodeURI(e)),xhr.send()}();

如果我将按钮拖到书签栏并从另一个站点单击它,它会重定向回localhost:3000并执行相同的操作。我错过了一些明显的东西吗?我无法在网上找到有关如何实施书签以发布当前网址的任何说明。

HTML看起来像这样:

  <a href='!function(){var e="http://localhost:3001/api/v1/links/bookmarklet?url="+document.location.href+"&id=1";xhr=new XMLHttpRequest,xhr.open("POST",encodeURI(e)),xhr.send()}();' id="button">post link</a>

我的Rails API的传入参数看起来像这样

<ActionController::Parameters {"url"=>"http://localhost:3000/!function()%7Bvar%20e=%22http://localhost:3001/api/v1/links/bookmarklet?url=%22 document.location.href %22", "id"=>"1", "xhr"=>"new%20XMLHttpRequest,xhr.open(%22POST%22,encodeURI(e)),xhr.send()}()", "format"=>:json, "controller"=>"api/v1/links", "action"=>"create_link_from_web"} permitted: false>

所以它确实在Rails中发布了正确的路线,但它们都搞砸了。非常感谢您的建议!

1 个答案:

答案 0 :(得分:0)

您的href属性被视为字符串中没有明确协议的相对路径,例如http:javascript:等。这就是它将原始域添加到您的网址字符串的原因。

请注意,bookmarklet不适用于所有浏览器,因此请确保您至少与目标受众群体兼容。

要解决此问题,请将HTML更改为

<a href='javascript:!function(){var e="http://localhost:3001/api/v1/links/bookmarklet?url="+document.location.href+"&id=1";xhr=new XMLHttpRequest,xhr.open("POST",encodeURI(e)),xhr.send()}();' id="button">post link</a>
相关问题