inject Script In Cross-Domain iFrame on Action Button Click?

176 views
Skip to first unread message

John Gordon

unread,
Aug 14, 2024, 10:59:31 AM8/14/24
to Chromium Extensions
Goal:

When the user clicks a button in my Side Panel, the extension will paste text into a DOM element inside a cross-domain iFrame of the active tab.

Knowing I need a content script inserted into the cross-domain iFrame, i can't really figure out how to do it. 

I know that I can get permissions to inject a content script into the active tab when the user clicks the extension's action button, but that doesn't get me down to the cross-domain iframe.

I have successfully injected a content script into the cross-domain iFrame when the user right-clicks a textarea in the dom and selects my extension's context menu item. I use optional permissions and chrome.scripting.executeScript to do that. Is there some way I could use this technique in my Side Panel scenario?

Maybe I could detect if there's an iFrame in the active tab, get its iframe index and src attribute, then request optional host permissions on it so I could then inject a content script. 

Thanks for your thoughts!

Rajat Paharia

unread,
Aug 16, 2024, 2:26:20 PM8/16/24
to Chromium Extensions, John Gordon
Hi John - 

I don't totally understand what you're asking, but
chrome.scripting.executeScript can call a function in all the frames on a page. e.g.

let injectionResults = await chrome.scripting.executeScript({
target : {tabId : tab.id, allFrames : true},
func : someFunction,
args: [element]
});


Would that help solve your problem? - rajat

woxxom

unread,
Aug 17, 2024, 12:40:37 AM8/17/24
to Chromium Extensions, Rajat Paharia, John Gordon
Indeed, there's no good way to implement what you want, because the "activeTab" permission intentionally doesn't grant permissions to cross-origin iframes and the only solution is the optional permissions, but as you already observed only a context menu click event provides the iframe URL, so you can't use the same approach in a side panel.

A reliable way to find the URLs of iframes is to use chrome.webNavigation.getAllFrames, but it won't give you the visual size and position of the iframes, so on some sites the list will unnecessarily contain invisible stuff e.g. captcha.

Another approach is to inject a content script in the tab's main document and check all visible iframe elements (using getComputedStyle), but that won't be reliable as the iframe's src attribute may be absent or incorrect if the iframe navigated itself inside afterwards (this is rare though). You'll also need to check every element's shadow recursively by using chrome.dom.openOrClosedShadowRoot.
Reply all
Reply to author
Forward
0 new messages