0

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.

MCSharp
  • 1,068
  • 1
  • 14
  • 37
  • Aha! There's no need for `"content_script"` section in manifest as it's not connected to `executeScript`. Instead use [`allFrames: true` parameter of executeScript](https://developer.chrome.com/extensions/tabs#method-executeScript). See the linked duplicate post for an implementation example without messaging. – wOxxOm Nov 18 '15 at 15:50
  • Thanks guys! I think I can figure it out with this information.Will close question. – MCSharp Nov 18 '15 at 16:10

0 Answers0