Search code examples
javascriptjqueryhtmlfirefoxhref

Href link that calls Javascript function opens a new tab and doesn't work in Firefox


I'm creating a link that calls a javascript function in href attribute:

 <a class="product-link" target="_blank" href='javascript:functionToPostParameters("path", "parameters");'><span class="product-name">My Product Link</span></a>

My function is this:

function functionToPostParameters(path, params) {
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("target", "_blank");
form.setAttribute("action", path);

for (var key in params) {
    if (params.hasOwnProperty(key)) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);
        form.appendChild(hiddenField);
    }
}

    form.submit();
    return false;
};

When I use this link in Chrome, it calls the function, submit the form with parameters and a new tab is opened.

In Firefox, it opens a new tab and then calls the function, as the new tab doens't contain the function, this error is shown in the console of the new tab:

 ReferenceError: functionToPostParameters is not defined

Is there an error in the href value / js function that makes Firefox behave in that way?

Any approach is welcomed, using href for the link.


Solution

  • Ok, I found the cause of the problem.

    I want that after the post is done, it gets opened in a new tab.

    The problem was that Firefox needs two things:

    1. Form needs a submit button.
    2. Form needs to be appended to body in order to make submit works.
    

    The new code of my function:

    function functionToPostParameters(path, params) {
    
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("target", "_blank");
    form.setAttribute("action", path);
    
    for (var key in params) {
        if (params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);
            form.appendChild(hiddenField);
        }
    }
    
    var submitButton = document.createElement("input");// NEW  
    submitButton.setAttribute("type", "submit");// NEW  
    submitButton.setAttribute("value", "Click");// NEW  
    form.appendChild(submitButton);// NEW  
    document.body.appendChild(form); // NEW  
    
    form.submit();
    };
    

    Link html:

     <a class="product-link" target="_self" href="javascript:void(0);" onclick="javascript:functionToPostParameters('path', 'parameters');"><span class="product-name"> My product Link </span> </a>
    

    Hope it helps to someone else.