Aaronius / penpal

A promise-based library for securely communicating with iframes via postMessage.
MIT License
389 stars 56 forks source link

Penpal does not work with iframe sandbox attribute #33

Closed etamponi closed 5 years ago

etamponi commented 5 years ago

Hi :)

I am trying to use Penpal to communicate with a sandboxed iframe, but it does not work without the allow-same-origin flag:

<!-- THIS WORKS -->
<iframe src="sandbox.html" sandbox="allow-scripts allow-same-origin"></iframe>
<!-- THIS DOES NOT WORKS -->
<iframe src="sandbox.html" sandbox="allow-scripts"></iframe>

Unfortunately, I can't set allow-same-origin in the sandbox.

Any help? Thank you :)

etamponi commented 5 years ago

Found the solution :)

1) It is not possible to use an <iframe> added in the html file, this specific setup only works for dynamically generated iframes.

2) In connectToChild, childOrigin needs to be set to "null" (the string "null", not the value null).

Amazing library :)

An example:

In index.js:

import connectToChild from "penpal/lib/connectToChild";

const iframe = document.createElement("iframe");
iframe.src = "./iframe.html";
iframe.sandbox.add("allow-scripts");
document.body.appendChild(iframe);

const connection = connectToChild({
  iframe,
  childOrigin: "null",
});

(async () => {
  const child = await connection.promise;
  await child.prepare();
})();

In iframe.js (imported by iframe.html):

import connectToParent from "penpal/lib/connectToParent";

connectToParent({
  methods: {
    prepare() {
      console.log("Prepared!");
    },
  },
});