I'm trying to communicate from a web page to a packaged app. The idea is to have the web page read a number from a serial device. Because I want to access the serial device, I need a packaged app and can't use an extension. This is pretty similar to Keep Chrome Packaged App running in background? and it seems that Chrome documentation says this is possible.

How can I execute the chrome.runtime.sendMessage from a regular web page? When I do so, I get *Uncaught TypeError: Cannot read property 'sendMessage' of undefined. My simple function is:

function doFunction(){
    chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
      function(response) {
        if (!response.success)
          handleError(url);
      });
}

My packaged app loads and can access the serial ports. But my suspicion is the manifest isn't "enabling" the chrome.runtime of the regular webpage. Manifest.json:

{
  "name": "Hello World!",
  "description": "My first Chrome App.",
  "version": "0.1",
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "icons": { "16": "calculator-16.png", "128": "calculator-128.png" },
  "permissions": [
    "serial",
    "*://localhost/*"
  ],
  "externally_connectable": {
  "matches": [
      "*://localhost/*"]
}
}

Maybe it's the ://localhost/ which I'm using for testing. But Chrome does not complain.

Any ideas out there? Thanks in advance.

有帮助吗?

解决方案

Xan's comment did the trick.

While Chrome did not complain about *://localhost/*, it did not work. Chrome did complain about other combinations such as file://localhost/.

I added foo.com to host file and then served up my web page through a web server, and it worked! I can communicate from my web page to my packaged app.

Note that browsing to file://www.foo.com/hostpage.html did not work. But browing to http://www.foo.com:3000/hostpage.html did. (I'm using Rails, hence the 3000 port).

Morale of the story: When testing locally, you need to add an entry with a bogus second level domain to your host file.

Here's my manifest.json:

{
  "name": "RFID Tag Reader",
  "description": "Reads RFID Tags connected via USB reader",
  "version": "0.0.0.1",
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "icons": {
    "16": "rfid-16.png",
    "128": "rfid-128.png"
  },
  "permissions": [
    "serial",
    "*://www.foo.com/*",
    "*://arealsite.net/*"
  ],
  "externally_connectable": {
    "matches": [
      "*://www.foo.com/*",
      "*://arealsite.net/*"
    ]
  }
}

其他提示

Adding "*://localhost/*" to externally_connectable worked for me.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top