You cannot simply use messaging the same way you would use it in a content script from an arbitrary webpage's code.

There are two guides available in the documentation for communicating with webpages, which correspond to two approaches: (externally_connectable) (custom events with a content script)

Suppose you want to allow http://example.com to send a message to your extension.

  1. You need to specifically whitelist that site in the manifest:

      "externally_connectable" : {
        matches: [ "http://example.com" ]
      },
    
  2. You need to obtain a permanent extension ID. Suppose the resulting ID is abcdefghijklmnoabcdefhijklmnoabc

  3. Your webpage needs to check it's allowed to send a message, then send it using the pre-defined ID:

    // Website code
    // This will only be true if some extension allowed the page to connect
    if(chrome && chrome.runtime && chrome.runtime.sendMessage) {
      chrome.runtime.sendMessage(
        "abcdefghijklmnoabcdefhijklmnoabc",
        {greeting: "yes"},
        onAccessApproved
      );
    }
    
  4. Your extension needs to listen to external messages and probably also check their origin:

    // Extension's background code
    chrome.runtime.onMessageExternal.addListener(
      function(request, sender, sendResponse) {
        if(!validate(request.sender)) // Check the URL with a custom function
          return;
        /* do work */
      }
    );