21

i have following script

Parent Page(pair_pixel_filter.php):

 window.addEventListener("message", function(e) {
            $('#log').append("Received message: " + (e.data));
        }, false);
 $('.photo-upload-btn').click(function(event) {
            event.preventDefault();
            window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes");
        });

The Child Page

$.ajax({
            type: 'post',
            url: url,
            data: {
                base64data: dataURL
            },
            success: function(data) {
                window.opener.postMessage(data, "pair_pixel_filter.php");
                window.close(); }
        });

Basically opening a Popup and then doing some ajax on pop up and returning result to parent. But from Child i am getting this error.

Uncaught SyntaxError: Failed to execute 'postMessage' on 'Window': Invalid target origin 'pair_pixel_filter.php' in a call to 'postMessage'

noobie-php
  • 5,140
  • 14
  • 44
  • 87

1 Answers1

27

The 2nd parameter to postMessage is the "target origin". This is the domain where the page is located, not the name of the (php) file.

It needs to be something like:

window.opener.postMessage(data, "http://example.com");

See: https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
  • 1
    very true, i just found out that we need to pass Full path like `localhost/abc/mypage.php` – noobie-php Apr 29 '14 at 20:09
  • 1
    @noobie-php actually, javascript will ignore anything after the domain, so the target window will accept it if the host is localhost, even if the path is different. Therefore, passing `http://localhost/abc/mypage.php` as origin will have same effect as passing `http://localhost` or `http://localhost/literally/anything/xyz.php`. – Jay Dadhania Nov 07 '19 at 17:15