Currently, I'm exploring ways to send messages from a Chrome extension to a page view and wait for a response. Here's what I've tried so far:
In the extension's content_script.js:
window.addEventListener('message', function(event) {
console.log('content_script.js got message:', event);
// Check event.type and event.data
});
setTimeout(function () {
console.log('cs sending message');
window.postMessage({ type: 'content_script_type',
text: 'Hello from content_script.js!'},
'*' /* targetOrigin: any */ );
}, 1000);
The Javascript running on the webpage:
window.addEventListener('message', function(event) {
console.log('page javascript got message:', event);
});
setTimeout(function() {
console.log('page javascript sending message');
window.postMessage({ type: 'page_js_type',
text: "Hello from the page's javascript!"},
'*' /* targetOrigin: any */);
}, 2000);
Reference: Chrome extension - retrieving global variable from webpage
However, I discovered that using window.postMessage results in one-way communication and does not allow waiting for a response. Any ideas on how to achieve this?