如何在循环中将内容脚本数据发送到 Popup.html - Chrome 扩展

问题描述

这是清单版本 2。如果我使用直接 DOM 元素发送数据,此代码可以正常工作。它将正确发送 popup.html 中的数据。

 heading =  document.querySelector('.ddddd').innerHTML;
 newprice = document.querySelector('.pricem').innerHTML;

老实说,我不知道如何在 popup.html 中发送多个数据。我尝试了 for 循环,但出现了一些错误。我正在寻找点击复制网站 DOM 元素数据并将它们附加到 popup.html 中。

网站示例。

<ul>

<li class="ddddd"> Product 1 Title </li>
<li class="pricem"> 5143 </li>
<br>
<li class="ddddd"> Product 2 Title </li>
<li class="pricem"> 4143 </li>
<br>
<li class="ddddd"> Product 3 Title </li>
<li class="pricem"> 8143 </li>
<br>

</ul>
content.js

chrome.runtime.sendMessage({
    from: 'content',subject: 'showPageAction',});

  chrome.runtime.onMessage.addListener((msg,sender,response) => {
    if ((msg.from === 'popup') && (msg.subject === 'DOMInfo')) {
  
     heading =  document.querySelector('.ddddd').innerHTML;
     newprice = document.querySelector('.pricem').innerHTML;

      var domInfo = {
        title: heading,price: newprice,};
      response(domInfo);
    }
  });

popup.js

const setDOMInfo = info => {

    document.getElementById('title').innerHTML = info.title;
    document.getElementById('price').innerHTML = info.price;
    
  };

  window.addEventListener('DOMContentLoaded',() => {

    document.getElementById("runF").addEventListener("click",function() {
        chrome.tabs.query({
          active: true,currentwindow: true
        },tabs => {
          chrome.tabs.sendMessage(
              tabs[0].id,{from: 'popup',subject: 'DOMInfo'},setDOMInfo);
        });
    });

  });

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="popup.js"></script>
  </head>
  <body>
    <h3 style="font-weight:bold; text-align:center;">DOM Info</h3>
    <table border="1" cellpadding="3" style="border-collapse:collapse;">
      <tr>
        <td>Title: </td>
        <td><span id="title">N/A</span></td>
      </tr>
      <tr>
        <td>Price: </td>
        <td><span id="price">N/A</span></td>
      </tr>
      <br>
      <button id="runF">GO GO...</button>
    </table>
  </body>
</html>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...