I'm looking for a way to access the HTML or live code of the current page including the HTML inside Iframes in a Chrome Extension. Ideally I'd like to access the DOM and then output a string.
I have researched a lot on the topic and can't seem to find a working solution. I tried all_frames
with no success. I also tried getting the contents directly which resulted in a cross origin error.
I am new to extensions and not sure how to create this. Since chrome can display the live code natively, I don't see why a plugin can't have this access as well.
manifest.json
{
"name": "Iframe Source Test",
"version": "1.0",
"manifest_version": 2,
"description": "Get HTML from Iframe",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["getPagesSource.js"],
"all_frames":true
}
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>"]
}
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>
popup.js
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
window.onload = onWindowLoad;
getPagesSource.js
function DOMtoString(document_root) {
var frame = document_root.getElementsByTagName('iframe')[0];
console.dir(frame);
var frameContents = frame.contentDocument;
console.log(frameContents);
return frame;
}
chrome.runtime.sendMessage({
action: "getSource",
source: DOMtoString(document)
});
Checking the log, the frame can be accessed. Accessing the contents results in:
Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.