Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions extensions/iframe.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@
let height = -1; // negative means default
let interactive = true;
let resizeBehavior = "scale";
let latestMessage = null;
let isTrusted = false;

const updateFrameAttributes = () => {
if (!iframe) {
Expand Down Expand Up @@ -121,6 +123,14 @@
}
};

const handleFrameMessage = (e) => {
if (isTrusted) {
latestMessage = e.data;
Scratch.vm.runtime.startHats("iframe_whenMessage");
}
};
window.onmessage = handleFrameMessage;

Scratch.vm.on("STAGE_SIZE_CHANGED", updateFrameAttributes);

Scratch.vm.runtime.on("RUNTIME_DISPOSED", closeFrame);
Expand Down Expand Up @@ -247,6 +257,35 @@
},
},
},
"---",
{
opcode: "sendMessage",
blockType: Scratch.BlockType.COMMAND,
text: Scratch.translate("send message [MESSAGE] to iframe"),
arguments: {
MESSAGE: {
type: Scratch.ArgumentType.STRING,
defaultValue: "hello",
},
},
},
{
opcode: "clearMessage",
blockType: Scratch.BlockType.COMMAND,
text: Scratch.translate("clear iframe message"),
},
{
opcode: "whenMessage",
blockType: Scratch.BlockType.EVENT,
text: Scratch.translate("when message from iframe is sent"),
isEdgeActivated: false,
},
{
opcode: "iframeMessage",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("iframe message"),
disableMonitor: true,
},
],
menus: {
getMenu: {
Expand Down Expand Up @@ -290,6 +329,7 @@
async display({ URL }) {
closeFrame();
if (await Scratch.canEmbed(URL)) {
isTrusted = false;
createFrame(Scratch.Cast.toString(URL));
}
}
Expand All @@ -300,6 +340,7 @@
Scratch.Cast.toString(HTML)
)}`;
if (await Scratch.canEmbed(url)) {
isTrusted = true;
createFrame(url);
}
}
Expand Down Expand Up @@ -379,6 +420,20 @@
}
}
}

sendMessage({ MESSAGE }) {
if (isTrusted) {
iframe.contentWindow.postMessage(MESSAGE, "*");
}
}

clearMessage() {
latestMessage = null;
}

iframeMessage() {
return latestMessage;
}
}

Scratch.extensions.register(new IframeExtension());
Expand Down