I’m writing an extension to emulate a mobile device when the extension icon is clicked. This is the first version of the extension and it is hardcoded. I have successfully attached to the Chrome tab, but my commands are not working as expected. I am using Chrome version 79 with protocol version 1.3. The steps I have implemented are:
- Attach to the Chrome tab
- Use
Browser.getVersion
to check for the correct protocol version - Use
Emulation.canEmulate
to make sure Chrome can emulate a mobile device - Use
Emulation.clearDeviceMetricsOverride
to clear any metrics - Use
Emulation.setUserAgentOverride
to override the current user agent - Use
Emulation.setDeviceMetricsOverride
to emulate a mobile device - Use
Emulation.setTouchEmulationEnabled
to emulate mobile events
function EmulateMobileDevice(tabId) {
var protocolVersion = '1.3';
chrome.debugger.attach({
tabId: tabId
}, protocolVersion, function() {
if (chrome.runtime.lastError) {
alert(chrome.runtime.lastError.message);
return;
}
// Browser.getVersion
chrome.debugger.sendCommand({
tabId: tabId
}, "Browser.getVersion", {}, function(response) {
console.log(response);
});
// Emulation.canEmulate
chrome.debugger.sendCommand({
tabId: tabId
}, "Emulation.canEmulate", {}, function(response) {
console.log(response);
});
// Emulation.clearDeviceMetricsOverride
chrome.debugger.sendCommand({
tabId: tabId
}, "Emulation.clearDeviceMetricsOverride", {}, function(response) {
console.log(response);
// Emulation.setUserAgentOverride
chrome.debugger.sendCommand({
tabId: tabId
}, "Emulation.setUserAgentOverride", {
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
acceptLanguage: 'en',
platform: 'mobile'
}, function(response) {
console.log(response);
//Emulation.setDeviceMetricsOverride
chrome.debugger.sendCommand({
tabId: tabId
}, "Emulation.setDeviceMetricsOverride", {
width: 0,
height: 0,
deviceScaleFactor: 0,
mobile: true,
screenOrientation: { type: 'portraitPrimary', angle: 1}
}, function(response) {
console.log(response);
// Emulation.setTouchEmulationEnabled
chrome.debugger.sendCommand({
tabId: tabId
}, "Emulation.setTouchEmulationEnabled", {
enabled: true
}, function(response) {
console.log(response);
});
});
});
}); });}
I have referenced @paulirish for the same idea, but it is written for protocol version 1.1, which is now deprecated. I have also read the documentation for protocol version 1.3, but I am still unable to get it to work. Here is the screenshot of the background script I have logged:
Many thanks.