Chrome 使用index.html(主流网页,不是popup.html)如何将数据从content.js发送到background.js后才使用onClick方法?

rwqw0loc  于 9个月前  发布在  Go
关注(0)|答案(1)|浏览(115)

整个要点是从HTML页面发送一些数据(不是弹出窗口)到content.js页面时,激发onclick,然后将其发送到background.js文件执行一些功能的数据,但我面临着一些错误,以获得它。

index.html

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

字符串

Content.js

Chrome.runtime.sendMessage()方法在document.onLoad()中工作正常,但在普通函数中调用它时会出现问题

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

后台.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`)
  }
}

klr1opcd

klr1opcd1#

Chrome扩展程序不允许您拥有内联JavaScript(文档)。
相反,使用<button id="submitButton">Submit</button>为按钮分配一个id,并使用addEventListener()sendData()函数绑定为事件。

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

字符串

相关问题