diff --git a/doc/dev-guide-source/guides/content-scripts/using-postmessage.md b/doc/dev-guide-source/guides/content-scripts/using-postmessage.md index 594e429cc..e6ec5b9fd 100644 --- a/doc/dev-guide-source/guides/content-scripts/using-postmessage.md +++ b/doc/dev-guide-source/guides/content-scripts/using-postmessage.md @@ -59,6 +59,50 @@ argument to the constructor: } }); +## Timing Issues Using postMessage ## + +Content scripts are loaded according to the value of the +[`contentScriptWhen`](dev-guide/guides/content-scripts/loading.html) +option: until that point is reached, any attempt to send a message to +the script using `postMessage()` will trigger an exception, probably +the unintuitive message: + + +This is a generic message which is emitted whenever we try to +send a message to a content script, but can't find the worker +which is supposed to receive it. + + +
+Error: The page has been destroyed and can no longer be used.
+
+ +So code like this, where we create a panel and then +synchronously send it a message using `postMessage()`, will not work: + + var data = require("self").data; + + var panel = require("panel").Panel({ + contentURL: "http://www.bbc.co.uk/mobile/index.html", + contentScriptFile: data.url("panel.js") + }); + + panel.postMessage("hi from main.js"); + +[`port.emit()`](dev-guide/guides/content-scripts/using-port.html) +queues messages until the content script is ready to receive them, +so the equivalent code using `port.emit()` will work: + + var data = require("self").data; + + var panel = require("panel").Panel({ + contentURL: "http://www.bbc.co.uk/mobile/index.html", + contentScriptFile: data.url("panel.js") + }); + + panel.port.emit("hi from main.js"); + + ## Message Events Versus User-Defined Events ## You can use message events as an alternative to user-defined events: