I have an iframe where users can play/stop audio (using web audio api). But how can I stop audio if I hide that iframe? (e.g., by setting the CSS property containerDiv.css('display', 'none')). I've tried to clear the parent div with containerDiv.html(''), but audio inside iframe still keeps playing.
Asked
Active
Viewed 2,364 times
1
redcrow
- 1,743
- 3
- 25
- 45
-
You can't. Can you explain the use case as it might help us provide a different solution? – idbehold May 15 '14 at 20:11
-
I have a tetris game inside an iframe that appears when users complete a task, waiting for other tasks. The tetris application (in javascript as well) has sounds and controls to manage those. But, when a new task is ready, that iframe has to be hidden. Now the problem is that if users previously enabled audio, then it keeps playing. – redcrow May 15 '14 at 20:14
-
I assume you control the parent and child frames, in which case you can use the [postMessage API](https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage) to communicate with the iframe. This would allow you to send a message to the iframe telling it to stop the audio. – idbehold May 15 '14 at 20:17
-
Oh ok, I didn't know that. I'll try and I'll let you know. In the meantime, if you want, you can propose your answer so that I can vote it as solution. – redcrow May 15 '14 at 20:23
1 Answers
2
You can use the postMessage API to communicate with the iframe. This would allow you to send a message to the iframe telling it to stop the audio.
A script in the parent window:
// Assuming the origin of your iframe is http://example.org
function hideTetrisIframe(){
var iframe = document.getElementById('tetris');
iframe.style.display = 'none';
iframe.contentWindow.postMessage('stop', 'http://example.org');
}
A script inside the iframe:
window.addEventListener('message', function(event) {
if (event.data === 'stop') {
// Stop audio that's playing
}
}, false);
idbehold
- 16,833
- 5
- 47
- 74
-
Yes, I've already implemented a similar mechanism by following your last comment. But now I'm facing the following error: `Cannot read property 'postMessage' of undefined onMessageReceived`. Do you any idea? – redcrow May 15 '14 at 23:04
-
Ok, solved... using pure javascript it works fine. Previously I was using jquery to get the iframe, but it doesn't seem to work. Thank you! – redcrow May 15 '14 at 23:09
-
For a jquery solution, I've found this: http://stackoverflow.com/questions/1654017/how-to-expose-iframes-dom-using-jquery – redcrow May 15 '14 at 23:11