英文:
upgrading chrome extension from manifest version2 to v3, need to get clipboard text in background.js
问题
以下是您要求的代码部分的翻译:
// 在点击网页上的特定按钮时,我会调用一个控制台应用程序,该应用程序会将JSON字符串复制到剪贴板中,然后在Chrome扩展的background.js中获取剪贴板数据,并将其传递给在网页中显示的content.js。
**错误 / 挑战:**
1- 需要将剪贴板文本获取到background.js中的一个变量中。我能在content.js中获取到它,但我需要在background.js中获取到它。
2- 在background.js控制台中出现了以下两个错误,但扩展程序仍在运行
Unchecked runtime.lastError: 本地主机已退出。
Unchecked runtime.lastError: 在接收到响应之前,消息端口已关闭。
我的background.js如下所示:
var port = null;
var tabId = null;
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
tabId=sender.tab.id;
var hostName = "my.console.app";
port = chrome.runtime.connectNative(hostName);
port.onDisconnect.addListener(onDisconnected);
sendResponse({status: 'ok'});
return true;
});
function onDisconnected() {
port = null;
SendResponse();
}
// 在v3中,此函数需要升级到清单版本3,因为v3中的chrome.extension.getBackgroundPage不兼容
function SendResponse() {
bg = chrome.extension.getBackgroundPage();
bg.document.body.innerHTML = ""; // 清除背景页
var helper = null;
if (helper == null) {
helper = bg.document.createElement("textarea");
helper.style.position = "absolute";
helper.style.border = "none";
document.body.appendChild(helper);
}
// 将焦点放在文本区域上
helper.select();
// 在所选控件中执行粘贴,此处为文本区域
bg.document.execCommand("Paste");
// 将数据发送回content_script
chrome.tabs.sendMessage(tabId, { action: "MY_CUSTOM_EVENT", response: helper.value });
}
content.js
document.addEventListener("MY_CUSTOM_EVENT", function (data) {
chrome.runtime.sendMessage({ runConsoleApp: true }, response => {
});
});
async function copyToTheClipboard(textToCopy){
navigator.clipboard.readText()
.then(text => {
//console.log('Pasted content: ', text);
$('.simulateEidResponse').html(text).trigger('click');
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
}
英文:
Hi I am converting Google chrome extension from manifest version-2 to version-3
facing 2 issues those are mentioned below, but before that I will explain what extension in expected to do.
On click specific button on webpage I am calling console application that is copying JSON string in clipboard, then in chrome extension background.js I am getting clipboard data and passing it to content.js which is showing it in web page.
Errors / challenges:
1- Need to get clipboard text into a variable in background.js. I am able to get it in content.js but I need it to get it in background.js
2- I am getting these 2 error in background.js console, but extension is working
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
Unchecked runtime.lastError: Native host has exited.
Unchecked runtime.lastError: The message port closed before a response was received.
<!-- end snippet -->
My Background.js looks like this
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var port = null;
var tabId = null;
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
tabId=sender.tab.id;
var hostName = "my.console.app";
port = chrome.runtime.connectNative(hostName);
port.onDisconnect.addListener(onDisconnected);
sendResponse({status: 'ok'});
return true;
});
function onDisconnected() {
port = null;
SendResponse();
}
//this funciton need to upgrade to manifest version 3 because in v3 `chrome.extension.getBackgroundPage` is not compatible
function SendResponse() {
bg = chrome.extension.getBackgroundPage();
bg.document.body.innerHTML = ""; // clear the background page
var helper = null;
if (helper == null) {
helper = bg.document.createElement("textarea");
helper.style.position = "absolute";
helper.style.border = "none";
document.body.appendChild(helper);
}
//Focus the textarea
helper.select();
// perform a Paste in the selected control, here the textarea
bg.document.execCommand("Paste");
// Send data back to content_script
chrome.tabs.sendMessage(tabId, { action: "MY_CUSTOM_EVENT", response: helper.value });
}
<!-- end snippet -->
content.js
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
document.addEventListener("MY_CUSTOM_EVENT", function (data) {
chrome.runtime.sendMessage({ runConsoleApp: true }, response => {
});
});
async function copyToTheClipboard(textToCopy){
navigator.clipboard.readText()
.then(text => {
//console.log('Pasted content: ', text);
$('.simulateEidResponse').html(text).trigger('click');
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
}
<!-- end snippet -->
答案1
得分: 1
目前由于crbug.com/1404835,在后台脚本中没有办法执行此操作。将来的解决方法是使用execCommand + offscreen API。
唯一可靠的解决方案,无论标签是否聚焦,都是在内容脚本中使用document.execCommand("Paste")。
// background.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.runConsoleApp) {
chrome.runtime.connectNative('my.console.app')
.onDisconnect.addListener(() => sendResponse(true));
return true;
}
});
// content.js
document.addEventListener('MY_CUSTOM_EVENT', async e => {
await chrome.runtime.sendMessage({ runConsoleApp: true });
document.querySelector('.simulateEidResponse').focus();
document.execCommand('selectAll');
document.execCommand('paste');
});
英文:
Currently there's no way to do it in the background script due to crbug.com/1404835.
In the future the workaround will be execCommand + offscreen API.
The only reliable solution that works regardless of whether the tab is focused or not is to use document.execCommand("Paste") in the content script.
// background.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.runConsoleApp) {
chrome.runtime.connectNative('my.console.app')
.onDisconnect.addListener(() => sendResponse(true));
return true;
}
});
// content.js
document.addEventListener('MY_CUSTOM_EVENT', async e => {
await chrome.runtime.sendMessage({ runConsoleApp: true });
document.querySelector('.simulateEidResponse').focus();
document.execCommand('selectAll');
document.execCommand('paste');
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论