Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active June 4, 2023 05:20
Show Gist options
  • Save dfkaye/0bf838ab2b731e62b4abac0185d4ece4 to your computer and use it in GitHub Desktop.
Save dfkaye/0bf838ab2b731e62b4abac0185d4ece4 to your computer and use it in GitHub Desktop.
CURRENTLY FAILING: pass messages to iframes and back

3 June 2023

HTML...

<iframe id="blankiframe"
    title="blank iframe example"
    width="0"
    height="0"
    sandbox="allow-scripts"
    src="about:blank"
    style="visibility: hidden";
>
<!-- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe -->
</iframe>

JavaScript version

Doesn't work from the console... Possibly due to anonymous iframe origin (no actual URL for it if we use iframe.src = '' or 'about:blank').

var iframe = document.createElement('iframe');

iframe.id = 'blankiframe';
iframe.title = 'blank iframe example';
iframe.width = '100';
iframe.height = '100';
iframe.sandbox = 'allow-scripts';
iframe.src = "about:blank";
// iframe.style = 'visibility: hidden';

iframe.onload = function (_) {
  // this runs...
  console.log("loading iframe message handler");
  console.log(iframe.contentWindow);

  // use this not self
  this.onmessage = function (request) {

    // this doesn't respond to postMessage
    // but does respond to iframe.onmessage({ data, source, origin })...

    var { data, origin, source } = request;

    console.log(data);
    console.warn(origin);
    console.log(source);
    console.warn(this);
    console.warn(self);
    
    source.postMessage("received", origin);
  };
};


self.document.documentElement.appendChild(iframe);

setTimeout(function () {

  self.onmessage = function (response) {
    console.error(response.data);
  };

  // sanity check, never can be too sure
  self.postMessage("self test");

  // this doesn't work (yet)... target mismatch message
  iframe.contentWindow.postMessage("sending", self.location);

  // this works but it probably should not...
  iframe.onmessage({ data: "direct message", origin: self.location.href, source: self })

}, 500);

Error messages

  • Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://duckduckgo.com') does not match the recipient window's origin ('null').
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment