IT박스

문자열로 저장된 JavaScript 코드 실행

itboxs 2020. 6. 9. 22:17
반응형

문자열로 저장된 JavaScript 코드 실행


문자열 인 JavaScript를 어떻게 실행합니까?

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    // how do I get a browser to alert('hello')?
}

eval("my script here")기능.


함수를 사용하여 실행할 수 있습니다. 예:

var theInstructions = "alert('Hello World'); var x = 100";

var F=new Function (theInstructions);

return(F());

eval함수는 전달 된 문자열을 평가합니다.

그러나 사용하는 eval것은 위험 할 수 있으므로 주의해서 사용하십시오.

편집 : annakata 좋은 포인트가 -입니다뿐만 아니라 eval 위험 , 그것이 느린 . 평가할 코드를 그 자리에서 파싱해야하기 때문에 일부 컴퓨팅 리소스가 필요하기 때문입니다.


eval ()을 사용하십시오.

평가의 W3 학교 투어 . 사이트에는 사용 가능한 평가 예가 있습니다. 모질라 문서는 이것을 자세히 다루고 있습니다.

이것을 안전하게 사용하는 것에 대해 많은 경고를받을 것입니다 . 사용자가 eval ()에 모든 것을 삽입하는 것을 허용하지 마십시오 . 큰 보안 문제입니다.

또한 eval ()의 범위 가 다르다는 것을 알고 싶을 것 입니다.


이 시도:

  var script = "<script type=\"text/javascript\"> content </script>";
  //using jquery next
  $('body').append(script);//incorporates and executes inmediatelly

개인적으로 테스트하지는 않았지만 작동하는 것 같습니다.


@Hossein Hajizadeh alerady가 말한 것과 조금 비슷 하지만 더 자세히 설명합니다.

에 대한 대안이 eval()있습니다.

이 함수 setTimeout()는 밀리 초 간격으로 무언가를 실행하도록 설계되었으며 실행되는 코드는 문자열로 형식화됩니다.

다음과 같이 작동합니다.

ExecuteJavascriptString(); //Just for running it

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    setTimeout(s, 1);
}

1 문자열을 실행하기 전에 1 밀리 초 동안 대기한다는 의미입니다.

가장 올바른 방법은 아니지만 작동합니다.


아래와 같이 eval사용하십시오 . Eval은주의해서 사용해야하며, " eval is evil " 에 대한 간단한 검색은 몇 가지 포인터를 던져야합니다.

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    eval(s);
}

복잡하고 난독 화 된 많은 스크립트에서이를 확인했습니다.

var js = "alert('Hello, World!');" // put your JS code here
var oScript = document.createElement("script");
var oScriptText = document.createTextNode(js);
oScript.appendChild(oScriptText);
document.body.appendChild(oScript);

특정 시간 후에 특정 명령 (문자열)을 실행하려면-cmd = your code-InterVal = delay to run

 function ExecStr(cmd, InterVal) {
    try {
        setTimeout(function () {
            var F = new Function(cmd);
            return (F());
        }, InterVal);
    } catch (e) { }
}
//sample
ExecStr("alert(20)",500);

new Function('alert("Hello")')();

이것이 최선의 방법이라고 생각합니다.


eval(s);

그러나 사용자가 데이터를 가져 오는 경우 위험 할 수 있지만 문제가 자체 브라우저에서 충돌하는 경우가 있습니다.


부정 행위인지 확실하지 않은 경우 :

window.say = function(a) { alert(a); };

var a = "say('hello')";

var p = /^([^(]*)\('([^']*)'\).*$/;                 // ["say('hello')","say","hello"]

var fn = window[p.exec(a)[1]];                      // get function reference by name

if( typeof(fn) === "function") 
    fn.apply(null, [p.exec(a)[2]]);                 // call it with params

나는 비슷한 질문에 대답하고 그것을 사용하지 않고 이것을 달성하는 방법에 대한 또 다른 아이디어를 얻었습니다 eval().

const source = "alert('test')";
const el = document.createElement("script");
el.src = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
document.head.appendChild(el);

In the code above you basically create Blob, containing your script, in order to create Object URL (representation of File or Blob object in browser memory). Since you have src property on <script> tag, the script will be executed the same way as if it was loaded from any other URL.


For users that are using node and that are concerned with the context implications of eval() nodejs offers vm. It creates a V8 virtual machine that can sandbox the execution of your code in a separate context.

Taking things a step further is vm2 which hardens vm allowing the vm to run untrusted code.

const vm = require('vm');

const x = 1;

const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.

const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);

console.log(sandbox.x); // 42
console.log(sandbox.y); // 17

console.log(x); // 1; y is not defined.

eval should do it.

eval(s);

New Function and apply() together works also

var a=new Function('alert(1);')
a.apply(null)

function executeScript(source) {
    var script = document.createElement("script");
    script.onload = script.onerror = function(){ this.remove(); };
    script.src = "data:text/plain;base64," + btoa(source);
    document.body.appendChild(script);
}

executeScript("alert('Hello, World!');");

eval(s);

Remember though, that eval is very powerful and quite unsafe. You better be confident that the script you are executing is safe and unmutable by users.

참고URL : https://stackoverflow.com/questions/939326/execute-javascript-code-stored-as-a-string

반응형