首页 > 解决方案 > 使用 executeScript 和 SendMessage 的 chrome 扩展中的执行顺序

问题描述

我想按此顺序执行以下操作
1. 用户在弹出窗口中单击按钮 (id='copyDetails')
2. 来自用户页面上的特定元素(包括名称字段)的文本存储在哈希中并发送到 background.js
3. 来自第 2 步的哈希存储在 chrome 存储中
4. 获取名称值(这是来自第 2 步的哈希中的一个键)并将其插入到弹出窗口中的元素 (id='firstName')

以下代码执行了上述所有步骤,但顺序错误(当前执行步骤 1、4、2、3)

popup.js

let copyDetails = document.getElementById('copyDetails');

// This gets the most recently stored name and inserts it into the firstName element (works fine) 
chrome.storage.sync.get(['key'], function(result) {
  document.getElementById('firstName').innerHTML = result.key.firstName;
});

copyDetails.onclick = function(element) {
  chrome.extension.getBackgroundPage().console.log("Step 1 - User clicks button");

  // the executeScript gets the DOM from the users current page, and extracts the relevant information for the different customer details (inc. name)
  chrome.tabs.executeScript({
    code: '(' + modifyDOM + ')();'
  }, (results) => {
    const customerDetails = results[0];

    chrome.runtime.sendMessage({customerDetails: customerDetails}, function(response) {
      chrome.extension.getBackgroundPage().console.log("Step 2 - send message");
    });
  });

  chrome.storage.sync.get(['key'], function(result) {
    chrome.extension.getBackgroundPage().console.log("Step 4 - retrieve name from storage and insert it into popup html element");
    document.getElementById('firstName').innerHTML = result.key.firstName;
  });
};

function modifyDOM() {
    const customerDetails = {
      firstName: document.getElementById('customer_first_name').innerHTML,
      lastName: document.getElementById('customer_last_name').innerHTML,
      email: document.getElementById('customer_email_address').innerText.split('Generate Email')[0].slice(0, -1),
      postcode: document.getElementById('customer_uk_postcode').innerHTML
    }
    return customerDetails
}

这里是background.js file

  function (request, sender, sendResponse) {
    chrome.storage.sync.set({key: request.customerDetails}, function() {
       chrome.extension.getBackgroundPage().console.log("Step 3 - save details in a hash in storage");
     });
  });

我想我需要在 executeScript 上使用回调,但是在玩了几个小时后,我无法让它工作。

完成的定义 = 我按下按钮 (id='copyDetails') 并在后台控制台中看到按顺序打印的步骤 1、2、3、4。

如有需要,popup.html

<!DOCTYPE html>
  <html>
    <head>
      <style>
        button {
          height: auto;
          width: auto;
          outline: none;
        }
      </style>
    </head>
    <body>
      <button id="copyDetails">Copy Details</button>
      <div class='details-button'>First Name: <button id="firstName">N/A</button></div>
      <script src="popup.js"></script>
    </body>
  </html>

和我的manifest.json

{
    "name": "Copy customer details",
    "version": "1.0",
    "description": "Copy customer details from an rfq with the click of a button!",
    "permissions": ["contextMenus", "activeTab", "declarativeContent", "storage"],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "page_action": {
      "default_popup": "popup.html"
    },
    "manifest_version": 2
}

标签: javascriptgoogle-chrome-extensionasynccallback

解决方案


推荐阅读