【问题标题】:using index.html(mainstream webpage, not a popup.html) how to send data from content.js to background.js only after onClick method?使用 index.html(主流网页,而不是 popup.html)如何仅在 onClick 方法之后将数据从 content.js 发送到 background.js?
【发布时间】:2021-11-24 05:56:12
【问题描述】:

重点是在触发 onclick 时将一些数据从 HTML 页面(不是弹出窗口)发送到 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`)
  }
}

【问题讨论】:

    标签: javascript html google-chrome google-chrome-extension selenium-chromedriver


    【解决方案1】:

    Chrome 扩展程序不允许您使用内联 JavaScript (documentation)。

    相反,为您的按钮分配一个 ID &lt;button id="submitButton"&gt;Submit&lt;/button&gt; 并使用 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))
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 2019-06-24
      相关资源
      最近更新 更多