Home > Back-end >  using index.html(mainstream webpage, not a popup.html) how to send data from content.js to backgroun
using index.html(mainstream webpage, not a popup.html) how to send data from content.js to backgroun

Time:10-04

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`)
  }
}

CodePudding user response:

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

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

Content.js

document.addEventListener('DOMContentLoaded', function() {
    const button = document.getElementById('submitButton');
    button.addEventListener('click', sendData);
});

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