Search code examples
javascripthtmlgoogle-chromegoogle-chrome-extensionselenium-chromedriver

using index.html(mainstream webpage, not a popup.html) how to send data from content.js to background.js only after onClick method?


The whole point is to send some data from HTML page(Not a popup window) to content.js page when fired a onclick and then send it to background.js file to perform some function with the data but i'm facing some errors to get it.

index.html

<input type="text" id='fullname' />
<button onclick="sendData()">Submit</button>

Content.js

chrome.runtime.sendMessage() method works fine when inside document.onLoad() but having an issue calling it inside a normal function

function sendData(){
    var fullName = document.getElementById('fullname').value;
    chrome.runtime.sendMessage({ "message": fullName }
    ,(res)=>console.log(res))
}

Background.js

chrome.runtime.onMessage.addListener(receiver);

function receiver(data, sender, sendResponse) {
  if (data.message !== undefined) {
    chrome.pageAction.show(sender.tab.id);
    sendResponse(`${data.message} is submitted as your fullname`)
  }
}


Solution

  • Chrome Extensions do not allow you to have inline JavaScript (documentation).

    Instead, assign an id to your button with <button id="submitButton">Submit</button> and use addEventListener() to bind the sendData() function as an event.

    Content.js

    document.addEventListener('DOMContentLoaded', () => {
        const button = document.getElementById('submitButton');
        button.addEventListener('click', sendData);
    });
    
    function sendData() {
        const fullName = document.getElementById('fullname').value;
        chrome.runtime.sendMessage({ "message": fullName }, (response) => console.log(response))
    }