0

Learning by following this https://www.youtube.com/watch?v=QukSh7ss7A8 and the code is here: https://github.com/pitops/design-review-chrome-extension

It's smooth sailing until I get to the part about onMessage. In particular, I'm stuck on this:

contentScript.js

const actions = {
    "toggle-designmode": toggleDesignMode,
    "get-state": getState,
    capture: captureVisibleTab,
    drawImage: drawImage,
};

chrome.runtime.onMessage.addListener((request, sender, response) => {
    const reply = actions[request.type] && actions[request.type](request.payload);
    reply && response(reply);
});

...

const getState = () => {
  const state = sessionStorage.getItem("state");

    return {
        type: "get-state",
        payload: state ? JSON.parse(state) : { designMode: document.designMode },
    };
};

This is triggered by popup.js

chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, message, function (response) {

This line in particularly confuses me the most:

const reply = actions[request.type] && actions[request.type](request.payload);

Haven't seen this kind of JS notation before, particularly the part about the payload with the braces?

Thanks!!!

anon123123
  • 25
  • 1
  • 4
  • `actions[request.type](request.payload)` implies that `actions[request.type]` is a function that is called with `request.payload` as the argument to that function ... `actions[request.type] &&` ensures that the function is only attempted if `actions[request.type]` is "truthy" (a function is truthy) - I guess `actions[request.type]` can only ever by "falsy" or a function ... if you understand `reply && response(reply)` then you understand this – Jaromanda X May 24 '20 at 23:32
  • Thanks Jaromanda X! What confuses me is that getState does not take any argument, so how does (request.payload) come into play? – anon123123 May 25 '20 at 14:45
  • Ohhh I get it! designMode is part of the Chrome API! So that's why it works like this! – anon123123 May 25 '20 at 15:41

0 Answers0