2017-07-15 79 views
0

我試圖製作一個將當前網址發佈到我的API的javascript書籤。例如,類似於Instapaper小書籤所做的事情。我寫了下面的腳本,通過一個縮小器並將它作爲href添加到我用作按鈕的<a>標記中。我希望能夠將此標籤拖動到書籤欄。製作一個可以發佈當前網址的javascript書籤

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上),它確實發出了發佈請求,但它將腳本本身添加到當前url頂部的地址欄中。

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()}();

如果我拖動按鈕,書籤欄和從其他網站點擊它,它重定向回本地主機:3000,做同樣的事情。我在這裏錯過了很明顯的東西嗎我無法在網上找到關於如何實現書籤以發佈當前URL的任何說明。

的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傳入PARAMS這個樣子

<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

你的HTML需要用'的

回答