Leave a Comment
window.postMessage
Используется для передачи сообщений между фреймами или открытыми всплывающими окнами.
Позволяет обходить same origin policy.
Также позволяет сделать костыль для того, чтобы не ждать минимальной задержки при setTimeout (сейчас по стандарту — 4мс) — https://developer.mozilla.org/ru/docs/DOM/window.setTimeout#Minimum_delay_and_timeout_nesting.
Подробнее — https://developer.mozilla.org/en-US/docs/DOM/window.postMessage.
Пример:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
/* * In window A's scripts, with A being on <http://example.com:8080>: */ var popup = window.open(...popup details...); // When the popup has fully loaded, if not blocked by a popup blocker: // This does nothing, assuming the window hasn't changed its location. popup.postMessage("The user is 'bob' and the password is 'secret'", "https://secure.example.net"); // This will successfully queue a message to be sent to the popup, assuming // the window hasn't changed its location. popup.postMessage("hello there!", "http://example.org"); function receiveMessage(event) { // Do we trust the sender of this message? (might be // different from what we originally opened, for example). if (event.origin !== "http://example.org") return; // event.source is popup // event.data is "hi there yourself! the secret response is: rheeeeet!" } window.addEventListener("message", receiveMessage, false); /* * In the popup's scripts, running on <http://example.org>: */ // Called sometime after postMessage is called function receiveMessage(event) { // Do we trust the sender of this message? if (event.origin !== "http://example.com:8080") return; // event.source is window.opener // event.data is "hello there!" // Assuming you've verified the origin of the received message (which // you must do in any case), a convenient idiom for replying to a // message is to call postMessage on event.source and provide // event.origin as the targetOrigin. event.source.postMessage("hi there yourself! the secret response " + "is: rheeeeet!", event.origin); } window.addEventListener("message", receiveMessage, false); |
Similar Posts
LEAVE A COMMENT
Для отправки комментария вам необходимо авторизоваться.