I am trying to copy an image into browser’s(specifically chrome) clipboard for later paste via ctrl + v or cmd + v. I tried 2 different way to implement that feature but failed. And note that this is a test automation framework, and this action should run in headless browser as well.
First Approach:
My previous code was (After data parsing):
if image_path.lower().endswith(".svg"):
mime_type = "image/svg+xml"
elif image_path.lower().endswith(".png"):
mime_type = "image/png"
else:
CommonUtil.ExecLog(sModuleInfo, "Unsupported file format. You can copy only PNG or SVG image.", 2)
return "zeuz_failed"
with open(image_path, "rb") as image_file:
image_data = image_file.read()
# Convert
image_b64 = base64.b64encode(image_data).decode('utf-8')
async_script = """
const base64Data = arguments[0];
const mimeType = arguments[1];
const callback = arguments[arguments.length - 1];
function b64toBlob(b64Data, contentType) {
contentType = contentType || 'image/png';
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 512) {
const slice = byteCharacters.slice(offset, offset + 512);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: contentType});
}
const blob = b64toBlob(base64Data, mimeType);
const item = new ClipboardItem({ [mimeType]: blob });
navigator.clipboard.write([item])
.then(() => callback(true))
.catch(async (err) => {
console.error('Standard clipboard failed:', err);
callback(false);
});
"""
success = selenium_driver.execute_async_script(async_script, image_b64, mime_type)
if success:
CommonUtil.ExecLog(sModuleInfo, f"The image ({mime_type}) successfully copied to clipboard.", 1)
return "passed"
else:
CommonUtil.ExecLog(sModuleInfo, "Failed to write image to clipboard", 3)
return "failed"
This code was working for Ubuntu & Windows’s chrome, but asking for clipboard write permission. so i was unable to bypass this permission by using this approach(if you can then please share the solution). It’s an automation test framework, so we can’t give permission manually.
Second Approach:
Then i tried another approach, which is, i will create temporary container for that image and place the image in DOM & copy via selecting, then simply copy the image. So i wrote this code:
if image_path.lower().endswith(".svg"):
mime_type = "image/svg+xml"
elif image_path.lower().endswith(".png"):
mime_type = "image/png"
else:
CommonUtil.ExecLog(sModuleInfo, "Unsupported file format. You can copy only PNG or SVG image.", 2)
return "zeuz_failed"
with open(image_path, "rb") as image_file:
image_data = image_file.read()
# Convert
image_b64 = base64.b64encode(image_data).decode('utf-8')
js_script = f"""
try {{
const tempDiv = document.createElement('div');
tempDiv.style.position = 'absolute';
tempDiv.style.left = '-9999px';
tempDiv.style.top = '-9999px';
tempDiv.contentEditable = 'true';
document.body.appendChild(tempDiv);
const img = document.createElement('img');
img.src = 'data:{mime_type};base64,{image_b64}';
tempDiv.appendChild(img);
// Select and copy
const range = document.createRange();
range.selectNodeContents(tempDiv);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
const success = document.execCommand('copy');
selection.removeAllRanges();
document.body.removeChild(tempDiv);
const event = new CustomEvent('copyImageResult', {{ detail: {{ success }} }});
document.dispatchEvent(event);
}} catch (error) {{
const event = new CustomEvent('copyImageResult', {{ detail: {{ error: error.message }} }});
document.dispatchEvent(event);
}}
"""
blob_script = f"""
return new Promise((resolve) => {{
const scriptBlob = new Blob([`{js_script}`], {{ type: 'application/javascript' }});
const scriptUrl = URL.createObjectURL(scriptBlob);
const script = document.createElement('script');
const nonce = document.querySelector('script[nonce]')?.nonce;
if (nonce) script.nonce = nonce;
script.src = scriptUrl;
document.addEventListener('copyImageResult', (e) => {{
URL.revokeObjectURL(scriptUrl);
script.remove();
resolve(e.detail);
}});
document.head.appendChild(script);
}});
"""
try:
result = selenium_driver.execute_script(blob_script)
if result.get('success'):
CommonUtil.ExecLog(sModuleInfo, f"Image copied to clipboard: {image_path}", 1)
return "passed"
else:
error_msg = result.get('error', 'Unknown error')
CommonUtil.ExecLog(sModuleInfo, f"Failed to copy image: {error_msg}", 3)
return "failed"
except Exception as e:
CommonUtil.ExecLog(sModuleInfo, f"JavaScript execution failed: {str(e)}", 3)
return "failed"
this code giving error in browser’s console:
utils_js.js:2716 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://127.0.0.1:*". Either the 'unsafe-inline' keyword, a hash ('sha256-QgRF5QQhYvcb8AOx8AIBAHlvrqLG1SyG/Jlfg9eyGlI='), or a nonce ('nonce-...') is required to enable inline execution.