Is it possible to run a Javascript code after page forwarding?

Asked

Viewed 333 times

1

I finished an online Javascript course and decided to create a simple program that allows me to open the page Google with the background of <body> in black.

My idea was to perform a redirect with the function location.assign and then modify the page using document, thus:

<!DOCTYPE html>

<html>
    <head>
        <title>Dark Google</title>
        <meta charset="utf-8">
    </head>

    <body>
        <script>
            location.assign("https://www.google.com");
            //Tentei também esse código: window.open("https://www.google.com","_self");
            document.body.style.background = "#000";
        </script>
    </body>
</html>

I did a lot of research on the internet about it before I came to ask here, but I was unsuccessful in my searches.

So my question is, how can I run a Javascript code after redirecting to a page without having to open the famous browser console and write the code manually ?

  • Thank you so much if you can answer my question and if someone found my question bad, it would be possible to explain to me what is wrong with it so I can correct it ?

  • 2

    Just using common sense, I believe the answer is no, it’s not possible. Allowing arbitrary code from one domain to run on another domain without any kind of permission is a very serious security breach.

  • If you want to do this, I suggest having an iframe inside the body and loading the page you want there, then you can customize that page by the code of your page

1 answer

8


It is impossible, at least through current browsers, to execute scripts on a page to which the user will be redirected. At least it’s meant to be, since they may exist flaws or unknown malicious exploits that allow this to be done.

And this impossibility is due to security reasons. Imagine if it were possible to execute scripts on the site to which I would redirect my user. It would, in this hypothetical situation, be possible to take the user to sites like banks and run scripts there. You could literally modify any site without even the original programmer knowing, and I don’t need to tell you how problematic that is. So I say it’s meant to be impossible.


However, if you are the person who maintains the site to which you want to redirect, you can create ways to make this possible. The simplest way to achieve something like this is to create a list of scripts predetermined and, based on some parameter passed in the URL, determine which script will be run. For example, you could create code in the back-end from your website that makes the append of a <script> before the end of your page to perform something.

Imagine that you want to redirect a user to another page of your website. You can do something like this:

window.location.replace('https://example.com/some-page?script=1);

And based on that 1 in the query script insert a script predetermined at the end of the HTML page. And you can create a list with several Ids predetermined by you. Each can render something predetermined at the bottom of the page.

If you are using PHP, it might be something like this:

<!-- O resto da sua página para cima... -->

<?php
  // Note que estamos comparando o valor que recebemos do usuário
  // (valor esse que não é confiável) através de uma string pré-determinada
  // por nós. No caso, esse ID 1, que irá renderizar um script pré-determinado.
  //
  // Nunca permita que um parâmetro passado pelo usuário seja executado. E se por
  // acaso houver essa necessidade (o que não é o caso aqui e na maioria das vezes),
  // certifique-se de fazer uma grande e minuciosa validação e outros cuidados com
  //  o valor passado.
  if ($_GET['script'] === '1') {
    echo '<script>';
    // Você já sabe o que tem nesse arquivo `meu-script-1.js` e sabe que
    // o usuário não poderá usá-lo de forma a quebrar a segurança.
    // Esse script foi pré-criado por você e tem meras funções de "efeitos"
    // programados por você, o administrador do site.
    echo file_get_contents('./meu-script-1.js');
    echo '</script>';
  }
?>

<!-- O resto da sua página para baixo... -->

I must emphasize the need for these scripts which I have mentioned to be predetermined. You NEVER should allow the user to execute arbitrary scripts on their pages. When some site does not protect itself against this, it is called XSS vulnerability (cross-site scripting), which is extremely serious. So if you want to implement something like this, read a lot about it so you don’t accidentally create a vulnerability for lack of attention to security. A good place to start understanding how XSS works is in this other question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.