【问题标题】:how do i pass selected text in chrome extension from background script to content script?如何将 chrome 扩展中的选定文本从后台脚本传递到内容脚本?
【发布时间】:2020-09-26 02:55:54
【问题描述】:

我正在构建一个本质上是抄袭检查器的扩展程序。因此,您复制文本,然后右键单击,然后您将被定向到我们的网站。现在,我想要做的是我想将所选文本从我复制的网站发送到我的网站输入页面,然后我想点击提交按钮。 为此,我需要执行这两行。

    document.getElementById("mycontent").value = "selected text";  
    document.getElementById("checkButton").click();    

但所选文本仅保留在 background.js 中,并且永远不会出现在内容脚本中,这就是我的扩展程序无法正常工作的原因。所以,我想知道如何解决这个问题,或者有没有其他方法可以输入我的文本并单击按钮。
背景.js

  var contextsList = ["selection"];

    for(i = 0;i<contextsList.length; i++){
        var context = contextsList[i];
        var titleX = " Check Plagiarism of Selected Text";
        chrome.contextMenus.create({title: titleX, contexts:[context], onclick: clickHandler, id: context });
    }
  function clickHandler(data, tab) {
         switch(data.menuItemId.id){
            case 'selection' :
             ex = encodeURIComponent(data.selectionText);
 var config = {content: ex};
chrome.tabs.executeScript(tab.id, {
    code: 'var config = ' + JSON.stringify(config)
}, function() {
    chrome.tabs.executeScript(tab.id, {file: 'contentScript.js'});
});
// background script
  chrome.runtime.onMessage.addListener((request,sender,sendMessage)=>{

if(request.type==="Getcontent"){
    const  content=// set your content 
    sendMessage({msg:"cont",content:content})

}

})

chrome.tabs.create({url: "https://greatseotools.net/plagiarism-checker"});


   break;

            }

         }

ContentScript.js

        //Content script 
chrome.runtime.onMessage.addListener((request,sender,sendMessage)=>{

    if(request==='content'){
     console.log("content",request.content)       
    }

})

//wrap this in an event 
chrome.runtime.sendMessage({
    type:'Getcontent'
})

manifest.json

    {
   "background": {
      "scripts": [ "background.js" ]
   },
   "browser_action": {
      "default_icon": "icons/19.png",
      "default_popup": "popup.html"
   },
   "content_scripts": [ {
      "all_frames": true,
      "js": ["contentScript.js" ],
      "matches": [ "*://*.greatseotools.net/*" ],
      "run_at": "document_end"
   } ],
   "description": "Check Plagiarism by just selecting text..",
   "homepage_url": "https://www.prepostseo.com/plagiarism-checker",
   "icons": {
      "128": "icons/128.png",
      "16": "icons/16.png",
      "48": "icons/48.png"
   },
    "manifest_version": 2,
   "name": "Plagiarism Checker for Chrome",
   "permissions": [ "activeTab","*://*/*", "https://ajax.googleapis.com/", "contextMenus" ],
   "update_url": "https://clients2.google.com/service/update2/crx",
   "version": "1.0"
}

我必须在其上输入文本并单击按钮的网站。

https://greatseotools.net/plagiarism-checker

【问题讨论】:

    标签: javascript jquery google-chrome-extension


    【解决方案1】:

    chrome.tabs.executeScript({file: 'contentScript.js'}) 这一行中,您没有将您的 selectionText 传递给内容脚本,您可以通过多种方式实现,这是我的两个建议:

    后台脚本

    1.使用chrome.tabs.executeScript api

     ex = encodeURIComponent(data.selectionText);
     var config = {content: ex};
    chrome.tabs.executeScript(tab.id, {
        code: 'var config = ' + JSON.stringify(config)
    }, function() {
        chrome.tabs.executeScript(tab.id, {file: 'content.js'});
    });
    

    内容脚本

    并且在您的内容脚本中,您应该能够检索 ex:

    alert('mycontent:' + config);
    

    2。在背景和内容脚本之间使用 chrome 消息 api

    后台脚本

      // background script
      chrome.runtime.onMessage.addListener((request,sender,sendMessage)=>{
    
    if(request.type==="Getcontent"){
        const  content=// set your content 
        sendMessage({msg:"cont",content:content})
    
    }
    
    })
    

    内容脚本

    //Content script 
    chrome.runtime.onMessage.addListener((request,sender,sendMessage)=>{
    
        if(request==='content'){
         console.log("content",request.content)       
        }
    
    })
    
    //wrap this in an event 
    chrome.runtime.sendMessage({
        type:'Getcontent'
    })
    

    3.使用 chrome 存储

    后台脚本

     chrome.storage.sync.set({'content':ex})
    

    内容脚本

    chrome.storage.sync.get(['content'], function(res) {
          console.log('Value currently is ' + res.content);
        });
    

    清单

    "permissions": ["storage"]
    

    【讨论】:

    • 你能告诉我应该把这段代码放在哪里吗?我的意思是我应该把哪些代码放在 background.js 中,哪些应该放在 contentscript.js 中
    • 我已经调整了答案让我知道它是否有效
    • 什么都没发生我已经编辑了我的问题,这就是我粘贴代码的方式。如果你觉得有什么不对,你可以告诉我。此外,您可以使用完整代码再次编辑您的答案,以便我可以使用它。
    • 您尝试同时使用这两种方法,首先尝试第一种,看看它是否适合您只使用 1 下的代码。使用 chrome.tabs.executeScript api
    • 我分别使用了这两个代码,但没有任何反应代码执行时没有错误,但控制台日志中没有任何内容,并且在警报代码中它说配置未定义。此外,在添加 id 之后,它只是停止执行里面的代码。我将在查询中添加清单,以便您检查是否有任何错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多