Reputation: 4537
In my extension, I have a content script that creates a <div>
containing an <iframe>
inside the current webpage (e.g. www.google.com). I load a page into the iframe, but the content has to be dynamic, so I post a bunch of HTML to the background page first using sendRequest
. The iframe page then queries the background page (again with sendRequest
), gets the HTML and adds it to the page's body.
The issue is that the iframe is not sized correctly when the dynamic content is added, so it has scrollbars. I would like to do something like this:
iframe.addEventListener("DOMContentLoaded", function(event) {
div.style.height = iframe.style.height = iframe.contentDocument.body.scrollHeight;
div.style.width = iframe.style.width = iframe.contentDocument.body.scrollWidth;
}, false);
Unfortunately I have two problems with this. First of all, the DOMContentLoaded
event is never fired (why?). Secondly, I presumably won't have access to iframe.contentDocument
anyway since iframe is loading from a different domain.
I could have the iframe use sendRequest
to post its size somewhere where the hosting page can get its hands on it. However, I am using the same code to insert the iframe into a popup window as well, so there's no easy way to send the request (since it will use chrome.tabs.sendRequest
for the content script but chrome.extension.sendRequest
for the popup window).
Any ideas about how to do this?
Upvotes: 2
Views: 1445
Reputation: 4537
Poked around a bit more and found a solution. The iframe, once it has loaded the dynamic content, calls:
var size = { height: document.body.scrollHeight, width: document.body.scrollWidth };
top.postMessage(JSON.stringify(size), "*");
The parent window contains:
window.addEventListener("message", function(event) {
var size = JSON.parse(event.data);
iframe.style.height = div.style.height = size.height + "px";
iframe.style.width = div.style.width = size.width + "px";
});
Upvotes: 3