0

I am trying (and failing) to create a chrome extension that when I click on the extension icon, the content script reads the active page which contains order information: order_num, name, order_details,etc (into chrome.local.storage) and then display this in the popup.html, so that I can contact a customer if a product is out of stock, (and theoretically save myself from having to draft an email every time).

I have been able to successfully get the information into chrome.local.storage, however, I cannot seem to get that information to display. When looking at the console.log, the content script seems to run after the populatePopup.js (which I am guessing is why it is not displaying).

I guess my question is that is using localStorage the best way to get information to the popup and is it possible to have the popup wait until after the content_bg.js has finished to load?

I am a complete noob and would truly value any assistance.

The folder structure is :

-manifest.json
-popup.html
-popup.js
-background.js
-popuatePopup.js
-content_bg.js
-content2.js
-disconnect.js
-message.js

Manifest.json

{
  "name": "CustomerContact",
  "version": "1.2",
  "manifest_version": 2,
  "description": "A must have extension for anyone at Janome Sewing Centre. This custom Chrome extension will collect information from the JSC site and puch the label information to the shipping services. In the end, rememeber this, in Adam I trust... granted not much... but more than Jebus",
  "permissions": [
    "https://www.readytoship.com.au/*",
    "storage",
    "activeTab",
    "tabs"
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "background": {
    "scripts": ["background.js"],
    "default_icon": "Contact-icon.png",
    "persistent": false
  }
}

content_bg.js

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

// Listen for messages from the popup.
chrome.runtime.onMessage.addListener((msg, sender, response) => {
  // First, validate the message's structure.
  if (msg.from === "popup" && msg.subject === "DOMInfo") {
    var keywords = "";
    chrome.storage.local.get("captured", function (result) {
      //console.log(result);
      keywords.captured = result;
      if (result.captured === true) {
        console.log("do nothing");
      } else {
        console.log("run content_nomsg");

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

        var email = document.getElementById("customerEmail").text;

        var orderTable = null;
        orderTable = document
          .getElementsByClassName("orderDetailItems")[0]
          .getElementsByClassName("infotable yui-dt-table")[0];

        var rowLength = orderTable.rows.length;

        var ttest = orderTable
          .getElementsByTagName("tbody")[0]
          .getElementsByTagName("tr");

        var arr = Array.prototype.slice.call(ttest);
        arr2 = arr.slice(1, rowLength - 4);
        arra = [];
        arr2.forEach(function (item, index, arr) {
          var line =
            arr[index].getElementsByTagName("td")[0].innerHTML +
            " X " +
            arr[index]
              .getElementsByTagName("td")[2]
              .getElementsByTagName("span")[0].innerHTML +
            " (Stock Code: " +
            arr[index].getElementsByTagName("td")[1].innerHTML +
            ")";
          arra.push(line);
        });
        var arraString = arra.join("\n");

        var custName = document
          .getElementsByClassName("orderDetailSummary")[0]
          .getElementsByClassName("infotable")[0]
          .getElementsByTagName("tbody")[0]
          .getElementsByClassName("yui-dt-even")[1]
          .getElementsByClassName("yui-dt-last")[0].innerHTML;

        var customerName = custName.substring(0, custName.indexOf("<br>"));
        var custName = customerName.trim();
        str = custName.split(" ");
        for (var i = 0, x = str.length; i < x; i++) {
          str[i] = str[i][0].toUpperCase() + str[i].substr(1).toLowerCase();
        }
        customerName = str.join(" ");

        var orderNum = document
          .getElementById("orderTitleBar")
          .getElementsByClassName("shippingOrderID")[0].innerHTML;

        var storArray = {
          src_orderNum: orderNum,
          src_custName: customerName,
          src_email: email,
          src_items: arraString,
        };

        chrome.storage.local.set({
          newStorage: storArray,
        });
        console.log(storArray);
        chrome.storage.local.set({ captured: true });
        var userPopup = {
          title: "",
          order: "",
        };
        chrome.runtime.sendMessage({ newStorage: storArray });
      }
      ///alert(result);
      //chrome.tabs.executeScript(null, { file: "populatePopup.js" });
      var domInfo = {
        custName: customerName,
        orderNum: orderNum,
        orderArray: arraString,
      };

      // Directly respond to the sender (popup),
      // through the specified callback.
      response(domInfo);
    });
  }
});

popup.html

<html>


  <style>
    html,
    body {
      font-family: arial;
    }
    table {
      border-collapse: collapse;
    }
    table tr td {
      border: 1px solid #000;
      padding: 10px;
    }
  </style>
  <body>
    <div>
      <button type="button" id="btnClear">Clear storage</button>
    </div>
    <div>
      <p>Step 1: Open the order</p>
      <button type="button" id="btnCapture">Capture Order Details</button>
      <div id="itemInfo">Placeholder</div>
    </div>
    <div>
      <p>Step 2: Select the type of email you are sending</p>
      <select id="SelEmailType"
        ><option id="1"
          >Out of Stock - Within 3 days (Order to be split)</option
        >
        <option id="2"
          >Out of Stock - Within 3 days (Order sent together later)</option
        >
        <option id="3">Backordered - (Order to be split/Offer Refund)</option>
        <option id="4">Backordered - (Offer wait or Refund)</option></select
      >
    </div>
    <div id"reactlike"></div>
    <div><p>Step 3: Select OOS/Backordered items</p></div>
    <div id="itemsBackordered">Placeholder</div>
    <div id="container"></div>
    <table id="excelDataTable"></table>

    <div>
      <p>Step 4: Create Email</p>
      <button type="button" id="btnCreateEmail">CREATE EMAIL</button>
    </div>
    <div>
      <p>To Do</p>

      <p>update record on order</p>
      <p>confirm email</p>
      <p>clear storage</p>
      <p>only active on rts</p>
    </div>
    <script src="popup.js"></script>
  </body>
</html>

popup.js

console.log("popup.js");
function doContent() {
  console.log("content1");
  chrome.tabs.executeScript(null, { file: "content_bg.js" });
}
function doContent2() {
  var emailSelect = document.getElementById("SelEmailType");
  var emailType = emailSelect.options[emailSelect.selectedIndex].id;
  var storedLegal = chrome.storage.local.get("newStorage", function (items) {
    if (items.newStorage.src_orderNum !== "undefined") {
      var custName = items.newStorage.src_custName;
      var orderNum = items.newStorage.src_orderNum;
      var email = items.newStorage.src_email;
      var arraString = items.newStorage.src_items;
      var orderList = items.newStorage.src_items;
      var orderArray = orderList.split("\n");
      var checkboxes = new Array();
      checkboxes = document.getElementsByTagName("input");
      console.log(checkboxes);
      for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].type == "checkbox") {
          if (checkboxes[i].checked === false) {
            console.log(i, "will be removed for the list");
            orderArray = orderArray.splice(i, 1);
          }
          console.log(i, checkboxes[i].checked);
        }
      }
      console.log("Out of Stock = ");
      console.log(orderArray);
      arraString = orderArray.join("\n");
      var storArray = {
        src_orderNum: orderNum,
        src_custName: custName,
        src_email: email,
        src_items: arraString,
        src_emailType: emailType,
      };

      console.log(storArray);
      chrome.storage.local.set({
        newStorage: storArray,
      });
    }
  });

  chrome.tabs.executeScript(null, { file: "content2.js" });
}

function clearStorage() {
  chrome.tabs.executeScript(null, { file: "disconnect.js" });
  alert("local cleared");
}
chrome.runtime.sendMessage({ popupOpen: true });
var port = chrome.runtime.connect();

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  console.log(message);
});
var x = 1;
var y = null; // To keep under proper scope
setTimeout(function () {
  x = x * 3 + 2;
  y = x / 2;
}, 1000);
var storedLegal = chrome.storage.local.get("newStorage", function (items) {
  if (items.newStorage.src_orderNum === "undefined") {
    // That's kind of bad
    console.log("ERROR");
  } else {
    //console.log(ArraArray);
    let orderNum = items.newStorage.src_orderNum;
    console.log("orderNum ", orderNum);
    let custName = items.newStorage.src_custName;
    console.log("custName ", custName);
    var newInput =
      "<p><strong>Order Number:</strong> " +
      orderNum +
      " (" +
      custName.trim() +
      ")</p>";
    document.getElementById("itemInfo").innerHTML = newInput;

    var orderList = items.newStorage.src_items;
    var orderArray = orderList.split("\n");
    //console.log(orderArray);

    // Draw HTML table
    var perrow = 2, // 3 cells per row
      html = "<table><tbody>";

    // Loop through array and add table cells
    for (var i = 0; i < orderArray.length; i++) {
      html +=
        "<tr><td><input type=" +
        "checkbox" +
        " " +
        "id=" +
        i +
        "/></td><td>" +
        orderArray[i] +
        "</td></tr>";

      var next = i + 1;
      if (next % perrow == 0 && next != orderArray.length) {
        html += "</tr><tr>";
      }
    }
    html += "</tbody></table>";

    // Attach HTML to container
    document.getElementById("container").innerHTML = html;
  }
});
//chrome.tabs.executeScript(null, { file: "populatePopup.js" });

//**************************** */
document.getElementById("btnCapture").onclick = doContent;
document.getElementById("btnCreateEmail").onclick = doContent2;
document.getElementById("btnClear").onclick = clearStorage;

background.js

chrome.runtime.onMessage.addListener((msg, sender) => {
  // First, validate the message's structure.
  if (msg.from === "content" && msg.subject === "showPageAction") {
    // Enable the page-action for the requesting tab.
    chrome.pageAction.show(sender.tab.id);
  }
});

chrome.runtime.onConnect.addListener(function (externalPort) {
  externalPort.onDisconnect.addListener(function () {
    console.log("onDisconnect");
    // Do stuff that should happen when popup window closes here
    chrome.tabs.executeScript(null, { file: "disconnect.js" });
  });

  console.log("onConnect");
});

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  var views = chrome.extension.getViews({
    type: "popup",
  });
  if (message.popupOpen) {
    chrome.tabs.executeScript(null, { file: "content_bg.js" });
    var x = 1;
    var y = null; // To keep under proper scope
    setTimeout(function () {
      x = x * 3 + 2;
      y = x / 2;
    }, 1000);
    chrome.runtime.onMessage.addListener(function (
      message,
      sender,
      sendResponse
    ) {
      console.log(message);
    });
    chrome.tabs.executeScript(null, { file: "populatePopup.js" });
  }
});

message.js

chrome.runtime.sendMessage({ popupOpen: true });

disconnect.js

console.log("Disconnect");
chrome.storage.local.clear();
//console.log(chrome.storage.local);

  • You don't need the background script, storage, messaging. Remove it all. All you need is chrome.tabs.executeScript, see [this answer](https://stackoverflow.com/a/4532567) that shows how to pass info from the content script. Also, there's no need for `alert`, it's better to use devtools for the popup: right-click inside the popup, then click "inspect". – wOxxOm May 31 '20 at 05:40

0 Answers0