7

I open a new tab using window.open. The new tab has a javascript myfunction function in it defined in a script tag. From the window that opens the new window, I want to run that function.

How can I do that?

Thanks

Something like

var a = window.open("mypage.html", "_blank");
a.myfunction("hi");

EDIT

This isn't working. Its not doing the alert.

opener

        var w = window.open("../scripts/map.php", "_blank");
        w.postMessage("The user is 'bob' and the password is 'secret'", "*");

new tab

        function receiveMessage(event) {
            alert(event.data);
        }
        window.addEventListener("message", receiveMessage, false);
8
  • Try using window.opener Commented Aug 27, 2014 at 1:58
  • 1
    How do I write the code exactly? Commented Aug 27, 2014 at 1:59
  • 2
    you can try a.postMessage and handle the message in that window. developer.mozilla.org/en-US/docs/Web/API/Window.postMessage Commented Aug 27, 2014 at 2:01
  • I think I misunderstood....you want to run myFunction, which is defined in the newly opened window, from the window that opened the new tab, right? It's not that you want to run a function in the opener window from the newly opened window, correct? Commented Aug 27, 2014 at 2:02
  • Do you want to run myFunction at any given time or only when the new window is opened? Commented Aug 27, 2014 at 2:06

2 Answers 2

13
var a = window.open("mypage.html", "_blank");
a.focus();

a.addEventListener('load', function(){
  a.myfunction("hi");
}, true);
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming a php file provides the content for the new window:

window.open('http://www.example.com/myFile.php?parameter=' + parameter, 'myWindow', 'width=500,height=500,scrollbars=yes').focus();

Then in the php section of myFile.php:

$myParam = (isset($_GET['parameter'])) ? $_GET['parameter'] : null;

Then using a body onload call a function:

<head>
<script>
    var myParam = '<?= $myParam ?>';
</script>
</head>
<body onload="myFunction()">

The function tests for the existence of $myParam:

function myFunction() {
    if (myParam) {
        //do Something
    }
}

1 Comment

I didn't want to attach it as a url parameter. The accepted answer works good though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.