2017-10-06 39 views
1

我打開使用window.location = 'http://api.soundcloud.com/resolve.json?url=' + trackUrl + '&client_id=5f9f5186993f64c91...';如何在頁面出錯時獲取頁面的URL或運行函數?

它拋出一個錯誤的頁面(有時是403,其他時間406,這似乎是隨機的),並防止剩餘的代碼運行。

我可以打開控制檯並運行我想在頁面出錯之前運行的代碼。

testURL= location.href; 
var trackId = testURL.match(new RegExp('/tracks/' + "(.*)" + '.json?')); 
alert(trackId[1]); 

由於某種原因,當我運行它時,原始URL會更改爲另一個,但它具有我需要的值。嘗試一下。

當我運行按照上述window.location將出現在地址欄中輸入:https://api.soundcloud.com/tracks/330724405.json?client_id=5f9f5186993f64c91...

我需要的值是在URL中330724405

所以,我需要的價值就在那裏。我怎樣才能以編程方式獲得它?

PS該用例用於錯誤處理不能自行解析的URL。這不是一個授權問題,特定的錯誤URL或故意禁用API。這是一個正確解析並返回JSON的地址(地址欄變化太像失敗!),你可以嘗試看到成功的解決方案:http://api.soundcloud.com/resolve.json?url=https://soundcloud.com/radioopensource/stuart-schwartz-on-hurricane-history-in-the-caribbean&client_id=5f9f5186993f64c91...

回答

1

這是未經測試的,但是你可以使用XMLHttpRequest()和regex responseURL ?也許洗刷this.status 403或406和readyState。

var trackUrl = "https://soundcloud.com/shinedownofficial/it-all-adds-up"; 
var xhr = new XMLHttpRequest(); 
xhr.open('GET', "http://api.soundcloud.com/resolve.json?url=" + trackUrl + " + client_id=5f9f5186993f64c91b1bb5cf43fe4b08", true); 

xhr.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
    console.log(xhr.responseURL); 
    'you can put your regex query here... 
    } 
}; 

xhr.send(); 
+0

謝謝!地址欄中的URL不會更改,但代碼將從406停止。該值位於控制檯內的錯誤消息中。所以,沒有worko。 – user1452893

+1

啊,我改變爲!==狀態和地位,似乎工作。我不會太激動,因爲它需要更多的測試。謝謝! – user1452893

+0

是的,我認爲200只是成功的。 – ApolloSoftware