![](/img/trans.png)
[英]Issue with javascript escape, encodeURI and encodeURIComponent
[英]Spotify Apps Api - encodeURI / escape
使用JavaScript函數encodeURI / escape和encodeURIComponent時似乎存在一個錯誤。 例:
escape( 'The Frames' ) // The 0.000000rames
encodeURI( 'The Frames' ) // The 0.000000rames
encodeURIComponent( 'The Frames' ) // The 0.000000rames
注釋顯示輸出。 在任何可以正常工作的瀏覽器中的Spotify外部執行此代碼(用+或%20替換空格)。
其他人可以確認這是一個錯誤嗎? 還是我在這里做錯了...? 是否可以報告Spotify應用程序的錯誤?
編輯:顯然上面的示例按預期方式工作。 但是,將它們合並到alert()中將顯示混亂的字符串,而實際上是可以的。
根據准則 :
編碼字符串
為確保應用程序不會以可能不安全的方式使用字符串,對Spotify API提供的所有字符串均進行了編碼,以便意外濫用不會造成注入漏洞。 如果應用程序未使用以下兩種方法解碼這些字符串,則這些字符串將作為垃圾顯示給用戶。 唯一的例外是URI,它從未被編碼,因此不需要解碼。 API文檔說明了每種方法必須解碼或不解碼的字符串。 JavaScript字符串中已添加了兩個方法: decodeForText()和decodeForHTML() 。 如果打算以安全的方式使用字符串,例如設置innerText或使用document.createTextNode()創建文本節點,則應使用encodeForText()。 它將返回原始的非轉義字符串,因此請確保不要將其插入任何將被解釋為HTML的上下文中。 如果將字符串放入innerHTML或將要解釋為HTML的任何代碼段中,則必須使用encodeForHTML()。 它將確保<和>編碼為<和>等。例如:
getElementById('song-title').innerHTML = track.title.decodeForHTML(); getElementById('song-title').innerText = track.title.decodeForText(); getElementById('song-title').appendChild(document.createTextNode(track.title.decodeForText()));
不使用這些方法的應用程序將a)無法顯示Spotify API中的元數據或任何其他數據,並且b)在上載過程中將被拒絕。 還要確保您正確地從不安全的HTML字符串(例如后端服務器)中逃脫了它們。
還有源代碼,以防您好奇:
String.prototype.decodeForText = function() {
var result = "";
for (var i = 0; i < this.length; ++i) {
if (this.charAt(i) !== "&") {
result += this.charAt(i);
continue;
} else if (this.substring(i, i + 5) === "&") {
result += "&";
i += 4;
continue;
} else if (this.substring(i, i + 4) === "<") {
result += "<";
i += 3;
continue;
} else if (this.substring(i, i + 4) === ">") {
result += ">";
i += 3;
continue;
} else if (this.substring(i, i + 6) === """) {
result += "\"";
i += 5;
continue;
} else if (this.substring(i, i + 6) === "'") {
result += "'";
i += 5;
continue;
} else if (this.substring(i, i + 8) === "=") {
result += "=";
i += 7;
continue;
}
}
return result;
};
String.prototype.decodeForHTML = function() {
return this;
};
String.prototype.decodeForLink = function() {
return encodeURI(this.decodeForText());
}
String.prototype.encodeToHTML = function() {
var result = "";
for (var i = 0; i < this.length; ++i) {
if (this.charAt(i) === "&") {
result += "&";
} else if (this.charAt(i) === "<") {
result += "<";
} else if (this.charAt(i) === ">") {
result += ">";
} else if (this.charAt(i) === "\"") {
result += """;
} else if (this.charAt(i) === "'") {
result += "'";
} else if (this.charAt(i) === "=") {
result += "=";
} else {
result += this.charAt(i);
}
}
return result;
}
}(this));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.