開発ツールが提供する高度な機能の一部には、chrome.debugger
APIを介してアクセスできます(debugger
マニフェストファイルにアクセス許可を追加します)。
Network.setUserAgentOverride
ユーザーエージェントは、次のコマンドを使用して変更できます。
// Assume: tabId is the ID of the tab whose UA you want to change
// It can be obtained via several APIs, including but not limited to
// chrome.tabs, chrome.pageAction, chrome.browserAction, ...
// 1. Attach the debugger
var protocolVersion = '1.0';
chrome.debugger.attach({
tabId: tabId
}, protocolVersion, function() {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError.message);
return;
}
// 2. Debugger attached, now prepare for modifying the UA
chrome.debugger.sendCommand({
tabId: tabId
}, "Network.enable", {}, function(response) {
// Possible response: response.id / response.error
// 3. Change the User Agent string!
chrome.debugger.sendCommand({
tabId: tabId
}, "Network.setUserAgentOverride", {
userAgent: 'Whatever you want'
}, function(response) {
// Possible response: response.id / response.error
// 4. Now detach the debugger (this restores the UA string).
chrome.debugger.detach({tabId: tabId});
});
});
});
サポートされているプロトコルとコマンドの公式ドキュメントは、ここにあります。執筆時点では、デバイスメトリックを変更するためのドキュメントはありません。しかし、Chromiumのソースコードを調べた後、現在知られているすべてのコマンドを定義するファイルを発見しました。
定義のリストを見ると、が見つかりますPage.setDeviceMetricsOverride
。このフレーズは私たちの期待に一致しているようです。さらに検索して、使用方法を見つけましょう。
これにより、「chromium / src / out / Release / obj / gen / devtools / DevTools.js」(数千行)が生成されます。どこかに、(美化された)定義する行があります:
InspectorBackend.registerCommand("Page.setDeviceMetricsOverride", [{
"name": "width",
"type": "number",
"optional": false
}, {
"name": "height",
"type": "number",
"optional": false
}, {
"name": "fontScaleFactor",
"type": "number",
"optional": false
}, {
"name": "fitWindow",
"type": "boolean",
"optional": false
}], []);
これを読む方法は?さて、あなたの想像力を使ってください:
chrome.debugger.sendCommand({
tabId: tabId
}, "Page.setDeviceMetricsOverride",{
width: 1000,
height: 1000,
fontScaleFactor: 1,
fitWindow: false
}, function(response) {
// ...
});
プロトコルバージョン1.0を使用してChrome25でこれをテストしましたが、機能します。デバッグ中のタブのサイズが変更されます。わーい!