0

这是清单版本 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>

4

0 回答 0