从清单版本2升级Chrome扩展到v3,需要在background.js中获取剪贴板文本。

huangapple go评论86阅读模式
英文:

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) =&gt; { 
tabId=sender.tab.id;
var hostName = &quot;my.console.app&quot;;
port = chrome.runtime.connectNative(hostName);
port.onDisconnect.addListener(onDisconnected);
sendResponse({status: &#39;ok&#39;}); 
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 = &quot;&quot;; // clear the background page
var helper = null;
if (helper == null) {
helper = bg.document.createElement(&quot;textarea&quot;);
helper.style.position = &quot;absolute&quot;;
helper.style.border = &quot;none&quot;;
document.body.appendChild(helper);
}
//Focus the textarea
helper.select();
// perform a Paste in the selected control, here the textarea
bg.document.execCommand(&quot;Paste&quot;); 
// Send data back to content_script
chrome.tabs.sendMessage(tabId, { action: &quot;MY_CUSTOM_EVENT&quot;, response: helper.value });
}

<!-- end snippet -->

content.js

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

document.addEventListener(&quot;MY_CUSTOM_EVENT&quot;, function (data) {
chrome.runtime.sendMessage({ runConsoleApp: true }, response =&gt; {
});
});
async function copyToTheClipboard(textToCopy){
navigator.clipboard.readText()
.then(text =&gt; {
//console.log(&#39;Pasted content: &#39;, text);
$(&#39;.simulateEidResponse&#39;).html(text).trigger(&#39;click&#39;); 
})
.catch(err =&gt; {
console.error(&#39;Failed to read clipboard contents: &#39;, 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) =&gt; {
  if (msg.runConsoleApp) {
    chrome.runtime.connectNative(&#39;my.console.app&#39;)
      .onDisconnect.addListener(() =&gt; sendResponse(true));
    return true;
  }
});

// content.js

document.addEventListener(&#39;MY_CUSTOM_EVENT&#39;, async e =&gt; {
  await chrome.runtime.sendMessage({ runConsoleApp: true });
  document.querySelector(&#39;.simulateEidResponse&#39;).focus();
  document.execCommand(&#39;selectAll&#39;);
  document.execCommand(&#39;paste&#39;);
});

huangapple
  • 本文由 发表于 2023年1月9日 19:50:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定