|
408 | 408 | }//iframe |
409 | 409 |
|
410 | 410 |
|
| 411 | + |
| 412 | + |
| 413 | + run.iframe3 = function(js){ |
| 414 | + |
| 415 | + |
| 416 | +// Create the iframe |
| 417 | +const iframe = document.createElement("iframe"); |
| 418 | +document.body.appendChild(iframe); |
| 419 | + |
| 420 | +// HTML that will run inside the iframe |
| 421 | +const html = ` |
| 422 | +<!doctype html> |
| 423 | +<html> |
| 424 | + <body> |
| 425 | + <script type="module"> |
| 426 | + console.log("iframe module script loaded"); |
| 427 | + |
| 428 | + // Catch *everything* the iframe might throw |
| 429 | + window.addEventListener("error", (e) => { |
| 430 | + console.log("iframe error:", e.message); |
| 431 | + }); |
| 432 | + |
| 433 | + window.addEventListener("unhandledrejection", (e) => { |
| 434 | + console.log("iframe unhandledrejection:", e.reason); |
| 435 | + }); |
| 436 | + |
| 437 | + window.addEventListener("message", async (event) => { |
| 438 | + if (event.data?.type !== "run") return; |
| 439 | + |
| 440 | + console.log("iframe got message, code:", event.data.code); |
| 441 | + |
| 442 | + try { |
| 443 | + // Turn the incoming code into a module |
| 444 | + const blob = new Blob( |
| 445 | + [event.data.code], |
| 446 | + { type: "text/javascript" } |
| 447 | + ); |
| 448 | + const url = URL.createObjectURL(blob); |
| 449 | + |
| 450 | + console.log("importing user module:", url); |
| 451 | + |
| 452 | + await import(url); |
| 453 | + |
| 454 | + console.log("user module finished"); |
| 455 | + URL.revokeObjectURL(url); |
| 456 | + } catch (err) { |
| 457 | + console.log("import failed:", err); |
| 458 | + } |
| 459 | + }); |
| 460 | + </scr`+`ipt> |
| 461 | + </body> |
| 462 | +</html> |
| 463 | +`; |
| 464 | + |
| 465 | +// Load the iframe from a Blob URL |
| 466 | +const blob = new Blob([html], { type: "text/html" }); |
| 467 | +iframe.src = URL.createObjectURL(blob); |
| 468 | + |
| 469 | +// When iframe is ready, send some code |
| 470 | +iframe.addEventListener("load", () => { |
| 471 | + console.log("iframe loaded, posting message"); |
| 472 | + |
| 473 | + iframe.contentWindow.postMessage({ |
| 474 | + type: "run", |
| 475 | + code: js |
| 476 | + }, "*"); |
| 477 | +}); |
| 478 | + |
| 479 | + |
| 480 | + }//iframe3 |
| 481 | + |
| 482 | + |
| 483 | + |
411 | 484 | obj.kill = function(){return kill()} |
412 | 485 |
|
413 | 486 | function kill(){ |
|
0 commit comments