sharataka
sharataka

Reputation: 5132

How to fix issues sending data from web page to chrome extension?

I am trying to pass data from my webpage to the chrome extension.

manifest.json (I am trying to do this in my local environment first)

  "externally_connectable": {
    "matches": ["*://localhost/*"]
  }

In listen.js (a background script):

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    if (sender.url == blacklistedWebsite)
      return;  // don't allow this web page access
    if (request.openUrlInEditor)
        alert('test2');
        alert(request.openUrlInEditor);
  });

None of the alerts display above.

I got the extension ID of the unpacked chrome extension by viewing the ID when I navigate to chrome://extensions/. In my webpage in localhost environment

// DEVELOPMENT extension ID
var editorExtensionId = "fppgjikaoolnlcmdjalbfkmlcadcckmb";

var url = 'test';
// Make a simple request:
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
  function(response) {
    if (!response.success)
      handleError(url);
  });

When I run this. in the browser, I get an error saying:

Error in event handler for (unknown): TypeError: Cannot read property 'success' of undefined

I'm not sure where to begin debugging this.

Upvotes: 2

Views: 1300

Answers (2)

Aefits
Aefits

Reputation: 3467

After making a few changes in your code I am able achieve your goal.

See below the complete code.

manifest.json

{
  "manifest_version": 2,
  "name": "CS to Bg Communication",
  "version": "0.1",
  "background": {
    "scripts": ["listen.js"]
  },
  "content_scripts": [
    {
      "all_frames" : true,
      "matches": ["<all_urls>"],
      "js": ["contentscript.js"]
    }
  ],
  "browser_action": {
    "default_popup": "popup.html"
  },
  "externally_connectable": {
    "matches": ["*://localhost/*"]
  }
}

listen.js - the background script

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    blacklistedWebsite = 'http : / / yourdomain . com /';
    if (sender.url == blacklistedWebsite)
      return;  // don't allow this web page access
    if (request.openUrlInEditor) {
        alert('test2 - ' + request.openUrlInEditor);
        sendResponse({"success": true, "AckFromBG": "I have received your messgae. Thanks!"}); // sending back the acknowlege to the webpage
    }
});

contentscript.js - the content script - actually does nothing

console.log("this is content script");

web-page.html - The local web page

<html>
    <body>

        This page will will send some message to BG script

        <script type="text/javascript">
            // DEVELOPMENT extension ID
            var editorExtensionId = "fjaedjckfjgifecmgonfmpaoemochghb"; // replace with your extension ID
            var url = 'test';
            chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url}, function(response) {
                console.log(response);
                if (!response.success)
                    handleError(url);
            });
            function handleError(url) {
                console.log(url);
            }
        </script>
    </body>
</html>

Summary of changes:

  • Defined blacklistedWebsite - this was undefined.

  • Added sendResponse({"success": true, "AckFromBG": "I have received your messgae. Thanks!"}); to send back the acknowledgment to the webpage.

  • Define function handleError(url) { console.log(url); } this was not defined.

That's it. Hope this will solve your issue.

Upvotes: 7

Xan
Xan

Reputation: 77571

The error you are getting indicates that chrome.runtime.sendMessage is executed. This means that external messaging is set up correctly: otherwise, chrome.runtime.sendMessage wouldn't be exposed to your page's code.

I think the problem is here:

if (sender.url == blacklistedWebsite)
  return;  // don't allow this web page access

I suspect the problem is blacklistedWebsite being undefined; the code fails with a ReferenceError and no meaningful response is being sent. Since the onMessage listener terminates (even with an error), the calling code gets an undefined response.

Check your background console to confirm if that's the case; if you copied this partial example code but aren't using this blacklisting functionality, delete this branch.

In future, please make sure you understand what every line of code you copy does!

Upvotes: 0

Related Questions