[SalesForce] Visualforce onclick javascript redirect doesn’t work

I'm struggling with javascript redirect. I've got two buttons (google button is there just for a test):

<apex:commandButton onclick="toGoogle();" value="Google"/>
<apex:commandButton onclick="toImport();" value="Import"/>

And some js at the bottom of the page:

    function toGoogle() {

        redirectTo('http://www.google.com');
    }

    function toImport() {

        redirectTo('{!URLFOR($Page.MyImportPage)}');
    }

    function redirectTo(target) {

        if (inIframe()) {
           // step out of an iframe (if opened via iframe)
            window.top.location.href = target;
            return false;
        } else {
          window.location.href = target;
        }
    }

    function inIframe() {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }

It works perfectly well when opened via iframe but not when I open my page separately. I've also tried a simple version of redirect:

function toGoogle() {
        window.location.href = 'http://www.google.com';
    }

but it didn't work either! I've found some questions about javascript redirect in VF pages but simply setting window.location.href with the target url seemed to be working for other people. What am I doing wrong?

Best Answer

Try using plain html input tag:

<input type="button" value="Google" class="btn" onclick="toGoogle()" />
<input type="button" value="Import" class="btn" onclick="toImport()" />
Related Topic