Capturing previews of a webpage or its DOM elementsPublished on 16 January 2013
- Given the screenshot of part of the page, how can we crop out our element from the screenshot?
If you’re only interested in the code and not the explanation of the problem, click here.
The screenshot problem: imperfect solutions
The solution in this post is dependent on the fact that the Chrome extension API provides a function,
chrome.tabs.captureVisibleTab() (docs), for taking a screenshot of the visible part of a tab.
Picking out the element from the screenshot
captureVisibleTab() function only gives us a portion of the screen, we can’t simply use the offset (top, left) of the rendered element.
For example, in the figure below, let the shaded part of the screen be the part of the screen that we capture, and the Message Passing header, boxed in yellow, be the element that we want to capture. Given the position of the screenshot relative to the origin of the window (the black dots), we’ll compute the position of our element relative to the origin of the screenshot (the blue dots), then crop out that region.
captureVisibleTab()), but extensions and content scripts can communicate indirectly through message passing.
Make sure that these permissions are included in your
manifest.json, and add the functions to one of your content scripts.
screenshot.js (content script):
We do three things:
- Use the extension to capture a screenshot of the open tab, receiving a
data://URL to the image and sending it to the content script.
- In the content script, scale down the screenshot by drawing it to a canvas. The original image may be higher resolution than the actual window, so it needs to be scaled.
- Crop out the portion of the screenshot canvas that we need onto another canvas, now containing our element.
We add a listener in the background script of the extension. When a screenshot is requested, it will take a screenshot and send back the
Our content script will take two functions. One takes a screenshot of the page, and it accepts a callback argument after the screenshot has finished. When the screenshot is taken, we encode the current position of the window using jQuery’s
Our second function takes a jQuery element and returns a jQuery object referring to a canvas with the preview of that element. It computes the position of the element on the canvas. We use the version of
drawImage() (docs) with the most parameters.
If this helped, feel free to leave and comment and let me know.
It’s up to you what you want to use the screenshots of the elements for, but here’s an example of what the screenshots would look like in click-and-cross: