chrome扩展中使用executeScript和SendMessage

时间:2018-10-27 11:47:13

标签: javascript google-chrome-extension asynccallback

我要按此顺序执行以下操作
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
}

0 个答案:

没有答案