I build a chrome extension as isolated iframe, which gets injected to a website via the content.js
script. The user can access the extension via a shortcut. So if the user enters the shortcut the iframe pops up. Inside the iframe is an input field that I want to focus when the user enters the shortcut.
My first idea was to do something like this:
document.querySelector('iframe').contentWindow.document.getElementByid('#myInput').focus()
But this did lead to the following error:
Blocked a frame with origin samplepage.com from accessing a cross-origin frame. at chrome-extension://sampleapp/content.js:38:64
Then I have hereby found out that I need to set all_frames
to true inside the content_scripts
and tried this workaround for the same origin policy. So I put this inside content.js
const frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
and this inside my app.js
of the iframe
window.addEventListener('message', event => {
// IMPORTANT: check the origin of the data!
if (event.origin.startsWith('http://your-first-site.com')) {
// The data was sent from your site.
// Data sent with postMessage is stored in event.data:
console.log(event.data);
} else {
// The data was NOT sent from your site!
// Be careful! Do not use it. This else branch is
// here just for clarity, you usually shouldn't need it.
return;
}
});
But all of this didn't work neither.