onClick 핸들러 내의 JavaScript 코드 내에서 문자열을 어떻게 이스케이프합니까?
어쩌면 나는 이것에 대해 너무 열심히 생각하고 있지만 링크의 onClick 핸들러 내부의 일부 JavaScript 코드에서 문자열에 사용할 이스케이프를 파악하는 데 문제가 있습니다. 예:
<a href="#" onclick="SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;">Select</a>
<%itemid%>
및 <%itemname%>
템플릿 대체가 발생하는 곳이다. 내 문제는 항목 이름에 작은 따옴표와 큰 따옴표를 포함한 모든 문자가 포함될 수 있다는 것입니다. 현재는 작은 따옴표가 포함되어 있으면 JavaScript 코드가 손상됩니다.
내 첫 번째 생각은 템플릿 언어의 기능을 사용하여 항목 이름을 JavaScript로 이스케이프 처리하여 따옴표를 이스케이프 처리하는 것이 었습니다. 링크의 HTML을 깨뜨리는 큰 따옴표가 포함 된 문자열의 경우는 수정되지 않습니다. 이 문제는 일반적으로 어떻게 해결됩니까? 전체 onClick 핸들러를 HTML로 이스케이프해야합니까?
그렇다면 템플릿 언어의 이스케이프 함수가 괄호, 따옴표 및 세미콜론을 HTML 화하므로 정말 이상하게 보일 것입니다.
이 링크는 검색 결과 페이지의 모든 결과에 대해 생성되므로 결과 당 하나씩 생성해야하므로 자바 스크립트 태그 내에 별도의 메서드를 생성 할 수 없습니다.
또한 내가 일하는 회사에서 자체 개발 한 템플릿 엔진을 사용하고 있으므로 툴킷 별 솔루션은 나에게 쓸모가 없을 것입니다.
자바 스크립트에서 작은 따옴표는 "\ x27"로, 큰 따옴표는 "\ x22"로 인코딩 할 수 있습니다. 따라서이 방법을 사용하면 자바 스크립트 문자열 리터럴의 (이중 또는 작은) 따옴표 안에 있으면 문자열에 포함 된 따옴표가 "분리"될 염려없이 \ x27 \ x22를 사용할 수 있습니다.
\ xXX는 문자 <127이고 \ uXXXX는 유니 코드 이므로이 지식을 바탕으로 일반적인 화이트리스트를 벗어난 모든 문자에 대해 강력한 JSEncode 함수를 만들 수 있습니다 .
예를 들면
<a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a>
서버 측 언어에 따라 다음 중 하나를 사용할 수 있습니다.
.NET 4.0
string result = System.Web.HttpUtility.JavaScriptStringEncode("jsString")
자바
import org.apache.commons.lang.StringEscapeUtils;
...
String result = StringEscapeUtils.escapeJavaScript(jsString);
파이썬
import json
result = json.dumps(jsString)
PHP
$result = strtr($jsString, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"',
"\r" => '\\r', "\n" => '\\n' ));
Ruby on Rails
<%= escape_javascript(jsString) %>
, 각 매개 변수에 대한 하나의 각 숨겨진 스팬을 사용 <%itemid%>
하고을 <%itemname%>
하고 내부에 그 값을 기록.
예를 들어, 범위 <%itemid%>
는 다음과 같 <span id='itemid' style='display:none'><%itemid%></span>
으며 javascript 함수 SelectSurveyItem
에서 이러한 범위에서 인수를 선택합니다 innerHTML
. ' .
HTML에서 문자열 리터럴을 사용하지 말고 JavaScript를 사용하여 JavaScript 이벤트를 바인딩하십시오.
또한 당신이하고있는 일 을 정말로 알지 못한다면 'href = #'를 피하십시오 . 강박적인 미들 클릭 (탭 오프너)의 유용성을 크게 떨어 뜨립니다.
<a id="tehbutton" href="somewhereToGoWithoutWorkingJavascript.com">Select</a>
내 JavaScript 라이브러리는 jQuery입니다.
<script type="text/javascript">//<!-- <![CDATA[
jQuery(function($){
$("#tehbutton").click(function(){
SelectSurveyItem('<%itemid%>', '<%itemname%>');
return false;
});
});
//]]>--></script>
이와 같은 링크 목록을 렌더링하는 경우 다음과 같이 할 수 있습니다.
<a id="link_1" href="foo">Bar</a>
<a id="link_2" href="foo2">Baz</a>
<script type="text/javascript">
jQuery(function($){
var l = [[1,'Bar'],[2,'Baz']];
$(l).each(function(k,v){
$("#link_" + v[0] ).click(function(){
SelectSurveyItem(v[0],v[1]);
return false;
});
});
});
</script>
(최소로는 HTML 속성에 무슨 일 경우는 HTML 인코딩을해야합니다 >
에 >
<
로 <
와 "
에 "
IT), 그리고 그들이 당신의 자바 스크립트 인용을 방해하지 않도록 (백 슬래시) 작은 따옴표를 탈출.
이를 수행하는 가장 좋은 방법은 템플릿 시스템 (필요한 경우 확장)을 사용하는 것이지만 이스케이프 / 인코딩 함수 몇 개를 만들고 거기에 들어가는 모든 데이터를 둘 다 감쌀 수 있습니다.
And yes, it's perfectly valid (correct, even) to HTML-escape the entire contents of your HTML attributes, even if they contain javascript.
Another interesting solution might be to do this:
<a href="#" itemid="<%itemid%>" itemname="<%itemname%>" onclick="SelectSurveyItem(this.itemid, this.itemname); return false;">Select</a>
Then you can use a standard HTML-encoding on both the variables, without having to worry about the extra complication of the javascript quoting.
Yes, this does create HTML that is strictly invalid. However, it is a valid technique, and all modern browsers support it.
If it was my, I'd probably go with my first suggestion, and ensure the values are HTML-encoded and have single-quotes escaped.
Declare separate functions in the <head> section and invoke those in your onClick method. If you have lots you could use a naming scheme that numbers them, or pass an integer in in your onClicks and have a big fat switch statement in the function.
I have faced this problem as well. I made a script to convert single quotes into escaped double quotes that won't break the HTML.
function noQuote(text)
{
var newtext = "";
for (var i = 0; i < text.length; i++) {
if (text[i] == "'") {
newtext += "\"";
}
else {
newtext += text[i];
}
}
return newtext;
}
Use the Microsoft Anti-XSS library which includes a JavaScript encode.
First, it would be simpler if the onclick handler was set this way:
<a id="someLinkId"href="#">Select</a>
<script type="text/javascript">
document.getElementById("someLinkId").onClick =
function() {
SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;
};
</script>
Then itemid and itemname need to be escaped for JavaScript (that is, "
becomes \"
, etc.).
If you are using Java on the server side, you might take a look at the class StringEscapeUtils from jakarta's common-lang. Otherwise, it should not take too long to write your own 'escapeJavascript' method.
Is the answers here that you can't escape quotes using JavaScript and that you need to start with escaped strings.
Therefore. There's no way of JavaScript being able to handle the string 'Marge said "I'd look that was" to Peter' and you need your data be cleaned before offering it to the script?
Any good templating engine worth its salt will have an "escape quotes" function. Ours (also home-grown, where I work) also has a function to escape quotes for javascript. In both cases, the template variable is then just appended with _esc or _js_esc, depending on which you want. You should never output user-generated content to a browser that hasn't been escaped, IMHO.
I faced the same problem, and I solved it in a tricky way. First make global variables, v1, v2, and v3. And in the onclick, send an indicator, 1, 2, or 3 and in the function check for 1, 2, 3 to put the v1, v2, and v3 like:
onclick="myfun(1)"
onclick="myfun(2)"
onclick="myfun(3)"
function myfun(var)
{
if (var ==1)
alert(v1);
if (var ==2)
alert(v2);
if (var ==3)
alert(v3);
}
'Program Tip' 카테고리의 다른 글
다중 처리 : tqdm을 사용하여 진행률 표시 줄 표시 (0) | 2020.11.20 |
---|---|
Angular 애플리케이션에 여러 HTTP 인터셉터 추가 (0) | 2020.11.20 |
WHERE 절에서 별칭 사용 (0) | 2020.11.20 |
Wix에서 이전에 설치된 프로그램 버전을 업데이트하는 방법 (0) | 2020.11.20 |
postgreSQL에서 테이블 생성 (0) | 2020.11.20 |