Using chrome.runtime.sendmessage to communicate from a webpage to a packaged app

非 Y 不嫁゛ 提交于 2019-12-11 08:58:09

问题


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.


回答1:


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/*"
    ]
  }
}


来源:https://stackoverflow.com/questions/23531671/using-chrome-runtime-sendmessage-to-communicate-from-a-webpage-to-a-packaged-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!