Access HTML of an cross-origin iframe in a chrome extension content script via jQuery?

Viewed 387

I am working on a chrome extension that collects display ads served on a website for a study. I am trying to access the ad html through jquery as follows:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){   
if(request.todo == "CaptureAds"){
    frames = $('iframe')
    for(var iter=0;iter<frames.length;iter++){
        console.log('==================IFRAME====================')
        console.log('A')
        console.log(frames[iter])
        console.log('B')
        console.log(frames[iter].contentDocument)
        console.log('C')
        console.log(frames[iter].src)
    }
}

});

This gives me the following result:

An cross-origin iframe that I can print but cannot access to the html of

Two normal iframes that I can print and have access to their html as well

I have looked up multiple questions on stackoverflow and they lead to the postMessage method. In my case I dont have edit access to the iframe so I can't communicate between the two iframes as suggested in those solutions. Can someone please suggest a way to bypass the same-origin policy in this case without messing with the browser settings.

Here is my manifest:

{
"manifest_version": 2,
"name": "xyz",
"version": "1.0",
"description": "abc",
"icons": {
    "16": "images/get_started16.png",
    "32": "images/get_started32.png",
    "48": "images/get_started48.png",
    "128": "images/get_started128.png"
},
"page_action": {
    "default_icon": "images/get_started16.png",
    "default_popup" : "popup.html",
    "default_title": "example"
},
"background": {
    "scripts": ["eventPage.js"],
    "persistent": false
},
"content_scripts": [
    {
        "matches": ["https://www.example.com/*"],
        "js": ["content.js", "jquery-3.3.1.min.js"],
        "all_frames": true
    }
],
"permissions": ["activeTab","https://www.example.com/*","webNavigation"]

}

1 Answers

So - the good news is you already have "all_frames" : true in your code. You might want to have

"matches": [
        "<all_urls>"
      ],

in your manifest if you want to load this functionality across all of the webpages. For the who's the parent of who part - you'd have to construct a kind of a tree.

Basically your content scripts will be loaded in parent frame as well as the iframe in that frame. You can use the referrer property and get which URL loaded which page through

window.document.referrer

and your iframe should be pointing to your parent frame. I don't know your restrictions but I suppose you can figure out what was the parent page (or perhaps you already know?) so it would be a matter of saying Page A loaded Page B in an iframe. At that stage your content script is in both of them, so you have access to both of those.

Related