Reputation: 857
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.
Upvotes: 0
Views: 1236
Reputation: 73686
Sounds like all you need is to autofocus the input element once your iframe itself becomes focused.
content.js:
const iframe = document.createElement('iframe');
iframe.src = chrome.runtime.getURL('iframe.html');
iframe.style.cssText = '...............';
iframe.onload = () => iframe.focus();
document.body.appendChild(iframe);
iframe.js:
window.addEventListener('focus', () => {
document.getElementById('myInput').focus();
});
Note that all_frames
isn't necessary and won't work here because the iframe doesn't have web content, it's an extension page shown inside so content scripts won't autorun there.
Upvotes: 1