首页 > 解决方案 > 复制和粘贴交叉表 Chrome 扩展

问题描述

我正在尝试创建一个 chrome 扩展,该扩展从选项卡 A 复制一个值并将其粘贴到选项卡 B。我正在尝试使其工作,但我没有收到任何响应消息。这是我的代码:

内容脚本.js

var toCopy = "Copy: I am a String";
document.getElementById('btnCopy').onclick = doCopy;
 
function doCopy(){
    chrome.runtime.sendMessage(extId, {text: toCopy}, chrome => {
        console.log('Copied ' + toCopy + '!');
    });
}
 
var toPaste = "Get: textCopied";
document.getElementById('btnPaste').onclick = doPaste;
 
function doPaste(){
    chrome.runtime.sendMessage(extId, {text: toPaste}, chrome => {
        console.log('Pasted ' + toPaste + '!');
    });
}

背景.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.text.substring(0, 5) === "Copy:")
        chrome.storage.sync.set({'textCopied': text.substring(6, text.length)}, function () {
              console.log('saved!');
    });
    else if (message.text.substring(0, 4) === "Get:")
        chrome.storage.sync.get(['textCopied'], function (items) {
              console.log('Here is the copied text from before: ' + items);
    });
}

上下文:

我在 manifest.json 上定义了“inject.js”。运行“inject.js”后,它会将新文件“file1.js”附加到目标页面的标题中。'file1.js' 具有链接函数来替换和重新排序该目标页面中的某些字段,并且它还具有“复制”按钮的功能,我想使用该按钮从运行的选项卡中复制值扩展至我稍后将打开的另一个选项卡。所以,我在“file1.js”中定义了复制功能,而不是在“inject.js”中。如果我在“inject.js”中定义“chrome.storage.sync.set”语句,它会很好用,但我希望/需要在单击按钮后执行该函数。运行“file1.js”脚本时会出现该按钮(因为在“file1.js”内部 我创建并附加了复制按钮)所以我认为我必须在“file1.js”脚本中定义按钮操作,对吧?或者我可以使用我使用“file1.js”创建的按钮从“inject.js”调用函数吗?

答案

我只是将所有内容都放入“inject.js”中,现在它就像一个魅力一样工作。为帮助我的 wOxxOm 担保!

(有关更多信息,请参阅答案)

标签: javascriptgoogle-chrome-extension

解决方案


答案:

我只是将所有内容都放入“inject.js”中,现在它就像一个魅力一样工作。为帮助我的 wOxxOm 担保!

(有关更多信息,请参阅答案)


推荐阅读