访问跨源域的独立 iframe chrome 扩展

Access isolated iframe chrome extension of a cross origin domain

我构建了一个 chrome 扩展作为独立的 iframe,它通过 content.js 脚本注入网站。用户可以通过快捷方式访问扩展。因此,如果用户输入快捷方式,iframe 就会弹出。 iframe 内部是一个输入字段,我想在用户输入快捷方式时将其聚焦。

我的第一个想法是做这样的事情:

document.querySelector('iframe').contentWindow.document.getElementByid('#myInput').focus()

但这确实导致了以下错误:

Blocked a frame with origin samplepage.com from accessing a cross-origin frame. at chrome-extension://sampleapp/content.js:38:64

然后我有 found out that I need to set all_frames to true inside the content_scripts and tried this workaround 同源政策。所以我把它放在 content.js

里面
const frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');

这在我的 app.js 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; 
    } 
}); 

但是所有这些都不起作用。

听起来您所需要的只是在您的 iframe 本身获得焦点后自动聚焦输入元素。

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();
});

请注意,all_frames 不是必需的,也不会在这里工作,因为 iframe 没有网页内容,它是一个显示在里面的扩展页面,所以内容脚本不会在那里自动运行。