skip to Main Content

I’m trying to pass a variable to window.open() method. I would like to use that passed variable to the opened html file.

**<script>

        var value = document.getElementById("oper").value;
        const Gobtn = document.getElementById("Go");

        Gobtn.addEventListener("click", function (){
            window.open("calculate.html", value);
        });

    </script>**

I’m trying to open "calculate.html" and use the content of the variable named "value" in the "calculate.html" file. Thanks.

4

Answers


  1. You can pass the variable to the URL by including it as a parameter.

    You can do this like:

    window.open("calculate.html?value=" + value)
    

    For best practice, you should encode the variable as a URL safe variable, using encodeURIComponent().

    Then ofcourse in your new window, you can use getQueryParam(value) to retrieve the parameter.

    Login or Signup to reply.
  2. to passing variables i suggest you to look at this similar question:
    javascript : sending custom parameters with window.open() but its not working

    The second parameter is a target attribute, look at this documentation:
    Window open()

    Login or Signup to reply.
  3. Modify window.open() method to include the variable as a query parameter in the URL.

    <script>
        var value = document.getElementById("oper").value;
        const Gobtn = document.getElementById("Go");
    
        Gobtn.addEventListener("click", function () {
          
            var url = "calculate.html?value=" + encodeURIComponent(value);
            window.open(url);
        });
    </script>
    

    Retrieve the variable from the opened HTML file (calculate.html).

        <script>
        function retrieveParameter(paramName) {
        var queryParameters = new URLSearchParams(window.location.search);
        return queryParameters.get(paramName);}
    var testValue = retrieveParameter('value');
        
    console.log("Value received:", testValue);
    document.body.innerHTML = "Value received: " + testValue;
    </script>
    

    Might be this be a useful to you thanks.

    Login or Signup to reply.
  4. //window file
    <script>
        var Gobtn = document.getElementById("Go");
    
        Gobtn.addEventListener("click", function () {
            var value = document.getElementById("oper").value;
            var newWindow = window.open("calculate.html");
            newWindow.name = value; // Set the window.name property
        });
    </script>
    
    //For calculate.html
    <script>
        var value = window.name;
        console.log(value); // Example: print the value to the console
        // Use the value as needed
    </script>
    
        
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search