简体   繁体   English

Chrome 扩展:将消息从注入的脚本发送到内容脚本

[英]Chrome Extension: Sending message from Injected Script to Content Script

I'm trying to develop a chrome extension, it has to inject the script using OnUpdated and OnActivated Event Listener.我正在尝试开发一个 chrome 扩展,它必须使用OnUpdatedOnActivated事件监听器注入脚本。

My script is injecting properly but the problem is that how I can communicate with my background/service_worker script using my injected script我的脚本注入正确,但问题是我如何使用注入的脚本与我的后台/service_worker 脚本通信

This is image of my injected script which contain some kind of buttons Injected Script这是我的注入脚本的图像,其中包含某种按钮Injected Script

I've tried to access these element into content-script send message to background/service_worker but these elements aren't accessible in my content-script我试图将这些元素访问到内容脚本中,将消息发送到后台/service_worker,但我的内容脚本中无法访问这些元素

When I try to access element without injected script these elements are passing message correctly between content-script to background/service-worker Web page当我尝试在没有注入脚本的情况下访问元素时,这些元素在内容脚本到后台/服务工作者Web 页面之间正确传递消息

This is the Manifest MV3 Manifest.json这是Manifest MV3 Manifest.json

"content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "css": [
        "css/all.min.css",
        "css/camera.css"
      ],
      "js": [
        "js/content-script.js"
      ],
      "run_at": "document_end",
      "all_frames": false
    }
  ],
  "web_accessible_resources": [
    {
      "resources": [
        "*"
      ],
      "matches": [
        "<all_urls>"
      ],
      "use_dynamic_url": true
    }
  ]

This is my content-script.js这是我的content-script.js

var startRecording = document.getElementById('start-recording');
var stopRecording = document.getElementById('rec-stop'); 

if(startRecording){
    startRecording.addEventListener('click',()=> {
        chrome.runtime.sendMessage({recording_started: true}, function(response){
            console.log(response.result);
        })
    })
}
if(stopRecording){
    stopRecording.addEventListener('click',()=>{
        console.log('im stop')       
    })
}

startRecording is accessing element from non injected script which is working and startRecording正在从正在运行的非注入脚本访问元素,并且
stopRecording is accessing element from injected script which is not working well stopRecording正在访问注入脚本中的元素,但效果不佳

and after all this is my service_worker.js which i'm using to listening messages from content script毕竟这是我的service_worker.js ,我用它来收听来自内容脚本的消息

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('Service Workder ',message);
    if(message.recording_started){
        sendResponse({result: 'hello Im going from service worker'});
    }
    if(message.notification){
        sendResponse({result: 'Notification from service worker'});
    }
})

Basically my problem is to accessing the element of injected script in content-script and pass message to service_worker.js when injected element is clicked基本上我的问题是在content-script脚本中访问注入脚本的元素,并在单击注入元素时将消息传递给service_worker.js

This is how I'm injecting my script这就是我注入脚本的方式

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { 
    if(changeInfo.status == 'complete' && tab.status == 'complete' && tab.url !== 'undefined'){
        chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
            if(tabs[0].url?.includes('chrome://')) return undefined;
            var currentId = tabs[0].id;
            chrome.scripting.executeScript({
                target: {tabId: currentId, allFrames: false},
                files: ['js/camera.js'],
            });
        });
    }
})

Maybe I'm using the wrong method for message passing You should suggest me a better way to passing message between injected script and content-script Thanks也许我使用了错误的消息传递方法你应该建议我在注入脚本和内容脚本之间传递消息的更好方法谢谢

Based on the limited code provided and your explanation, if stopRecording is added via the injected script, then it does not appear that your codes actually adds the stopRecording element.根据提供的有限代码和您的解释,如果通过注入的脚本添加了 stopRecording,那么您的代码似乎并没有实际添加 stopRecording 元素。 Upon the user clicking "startRecording", you should be injecting the stopRecording element first into the DOM before attempting to "getElementId" and assign an onclick event to it.当用户单击“startRecording”时,您应该先将 stopRecording 元素注入 DOM,然后再尝试“getElementId”并为其分配 onclick 事件。 Inside the startRecording onClick event you should be adding code that replaces the startRecording Button with the stopRecording button and then looking for 'rec-stop':在 startRecording onClick 事件中,您应该添加将 startRecording 按钮替换为 stopRecording 按钮的代码,然后寻找“rec-stop”:

 var startRecording = document.getElementById('start-recording');
 
 if(startRecording){
    startRecording.addEventListener('click',()=> {
    //Replace startRecording Button with stopRecording Button
    const stopRecordingElement = document.createElement("div");
    stopRecordingElement.id = "rec-stop";
    //Add any image or styling to button
    startRecording.replaceWith(stopRecordingElement);
    //Now that the DOM has the 'rec-stop' element you can call
    var stopRecording = document.getElementById('rec-stop'); 
    if(stopRecording){
       stopRecording.addEventListener('click',()=>{
          console.log('im stop')       
       })
    }
    chrome.runtime.sendMessage({recording_started: true}, 
        function(response){
            console.log(response.result);
        })
    })
 }

I've tried to access my injected elements into my non-injected js files They are working properly for me我试图将我注入的元素访问到我的非注入 js 文件中,它们对我来说工作正常

Thanks everyone for helping me谢谢大家帮助我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从内容脚本发送消息到后台脚本会破坏chrome扩展 - Sending message from content script to background script breaks chrome extension Chrome 消息扩展:从注入的脚本到后台 - Chrome message extension : From injected script to background Chrome扩展程序:从注入的脚本向后台脚本发回消息时出错 - Chrome extension : error when sending message back from injected script to background script 将消息从后台脚本发送到内容脚本,然后发送到注入的脚本 - Sending message from a background script to a content script, then to a injected script 将消息发送到Chrome扩展程序中的内容脚本 - Sending message to Content Script in Chrome Extension Chrome扩展程序:将消息从后台发送到注入的脚本 - Chrome Extension: Send Message from Background to Injected Script 将消息从后台脚本发送到内容脚本,然后在Chrome扩展程序中进行响应 - Send message from background script to content script then response in chrome extension 无法从Chrome扩展程序中的后台脚本向内容脚本发送消息 - unable to send message from background script to content script in chrome extension Chrome扩展程序-从内容脚本向事件页面发送变量 - Chrome Extension - Sending variable from content script to event page 删除chrome扩展中的注入脚本 - Remove injected script in chrome extension
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM