Home > Back-end >  Inject and execute JavaScript into an existing DOM
Inject and execute JavaScript into an existing DOM

Time:03-16

I'm playing with inject JavaScript code into an existing DOM.

I've seen that if I put the script by hand in the browser's DOM elements inspector

<script>alert("XSS test");</script>

the script node is added to the DOM, but it has no effect. I mean, no alert box is shown.

screenshot

On the other hand, if I put the script as plain text through the JavaScript console using document.write(), in this case the code got parsed and executed immediately, and the alert box is shown as expected.

document.write('<script>alert("XSS test");</script>');

I'm used to see that hand made changes to the DOM elements in the inspector reflects immediately in the page, while it seems that JavaScript nodes are an exception.

Why web browsers do not execute JavaScript nodes put by hand in the inspector?

Is there another way to send the script node to the DOM and make it run immediately?

CodePudding user response:

script tags added via innerHTML and related methods (insertAdjacentHTML, etc.) are not executed. (The exact rules are somewhere in the script portion of the HTML specification but it's heavy going.) This may be because early on it was identified that poorly-written pages might use innerHTML and such to append user content, and so not executing it was a quick and simple way to avoid very, very basic XSS attacks. But only very, very basic ones.

You can add a script tag to the DOM and have it executed by creating and appending a script tag:

const script = document.createElement("script");
script.textContent = `console.log("Hi there");`;
document.body.appendChild(script);

You can do that from the console tab in devtools, for instance, rather than the DOM inspector tab.

CodePudding user response:

try going to the web page you want and then in the URL bar at the top add

javascript:[your script]

for example

javascript:alert("Hello World!");

  • Related