Skip to content

Instantly share code, notes, and snippets.

@yasu-s
Last active February 23, 2024 05:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yasu-s/1405183ba61876ba83dd5dcc4d0162f0 to your computer and use it in GitHub Desktop.
Save yasu-s/1405183ba61876ba83dd5dcc4d0162f0 to your computer and use it in GitHub Desktop.
Chrome拡張 - ScreenCapture Test
{
"manifest_version": 3,
"name": "ScreenCapture Test",
"version": "1.0",
"description": "ScreenCapture Test",
"permissions": ["activeTab", "debugger"],
"action": {
"default_popup": "popup.html"
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="margin: 0px; width: 100px;">
<div style="padding: 10px; background: lemonchiffon;">
<div>
<button id="btn">画像保存</button>
</div>
</div>
<script src="/popup.js"></script>
</html>
document.getElementById('btn').addEventListener('click', async () => {
// タブ情報取得
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// デバッガアタッチ
chrome.debugger.attach({ tabId: tab.id }, '1.3', async () => {
console.log('attach - ok');
// デバッガ起動待機
await new Promise((resolve) => setTimeout(resolve, 500));
// レイアウト情報取得
chrome.debugger.sendCommand({ tabId: tab.id }, 'Page.getLayoutMetrics', {}, (metrics) => {
// スクリーンショットパラメータ作成
const params = {
format: 'png',
quality: 50,
clip: {
x: 0,
y: 0,
width: metrics.cssContentSize.width,
height: metrics.cssContentSize.height,
scale: 1
},
captureBeyondViewport: true
}
// スクリーンショット撮影
chrome.debugger.sendCommand({ tabId: tab.id }, 'Page.captureScreenshot', params, (result) => {
// 画像保存
const downloadEle = document.createElement('a');
downloadEle.href = 'data:image/png;base64,' + result.data;
downloadEle.download = 'screenshot.png';
downloadEle.click()
// デバッガでタッチ
chrome.debugger.detach({ tabId: tab.id }, () => {
console.log('detach ok')
});
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment