使用index.html(主流网页,不是popup.html)如何仅在onClick方法后才将数据从content.js发送到background.js?
using index.html(mainstream webpage, not a popup.html) how to send data from content.js to background.js only after onClick method?
重点是在触发 onclick[=31= 时将一些数据从 HTML 页面(不是弹出窗口 window)发送到 content.js 页面] 然后将它发送到 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))
}
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`)
}
}
Chrome 扩展不允许内嵌 JavaScript (documentation).
相反,为您的按钮分配一个 ID <button id="submitButton">Submit</button>
并使用 addEventListener() 将 sendData()
函数绑定为一个事件。
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))
}
重点是在触发 onclick[=31= 时将一些数据从 HTML 页面(不是弹出窗口 window)发送到 content.js 页面] 然后将它发送到 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))
}
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`)
}
}
Chrome 扩展不允许内嵌 JavaScript (documentation).
相反,为您的按钮分配一个 ID <button id="submitButton">Submit</button>
并使用 addEventListener() 将 sendData()
函数绑定为一个事件。
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))
}