首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Chrome扩展NativeMessaging 'connectNative‘未定义

Chrome扩展NativeMessaging 'connectNative‘未定义
EN

Stack Overflow用户
提问于 2014-04-30 10:43:45
回答 2查看 6.5K关注 0票数 4

我正在尝试使用runtime.connectNative和postMessage实现一个chrome扩展。我遵循铬文档,下载了我试图运行的本机消息传递示例,没有任何更改,而本地主机应用程序的代码可以找到这里

但是,我得到了错误:未定义的TypeError:无法读取未定义的属性'connectNative‘。

此错误是从javascript扩展名文件中触发的,如下所示:

港口= chrome.runtime.connectNative(hostName);

当扩展从清单中加载时,如下所示:

代码语言:javascript
运行
复制
"app": {
   "launch": {
      "local_path": "main.html"
   }
}

请问有什么办法解决这个问题吗?

Chrome版本34,在windows 7,8.1上进行测试

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-08-07 23:35:53

当前的问题是,您没有正确地运行示例代码。更大的问题是Google没有提供关于如何使用这个示例代码的全面文档。

您引用的本机消息传递示例仅链接到Chrome扩展的示例代码。在搜索之后,我找到了本机消息传递主机应用程序的相关示例代码。要同时获得Chrome扩展和本地消息传递主机应用程序的示例代码,您需要下载nativeMessaging.zip。在这个zip文件中,您还可以找到一些关于如何在Windows、Linux和Mac上安装本机消息传递主机的简要说明。我现在将告诉您,这些说明是不完整的,因为它们没有告诉您如何安装Chrome扩展。此外,用于安装和卸载本机消息传递主机的脚本不能在OS上正常工作。请参阅下面的安装说明和更正的脚本。

如何安装示例扩展和本机主机应用程序

  1. 下载并解压缩nativeMessaging.zip文件。
  2. 安装Chrome扩展
    1. 在Chrome中,在地址栏中输入chrome://extensions/
    2. 点击“加载解压分机.”按钮
    3. 导航到解压缩的nativeMessaging目录,并选择要导入的app目录

  1. 安装本机消息传递主机应用程序
    1. 对于OS和Linux,您需要向一些文件添加执行权限。运行命令:chmod a+rx nativeMessaging/host/install_host.sh nativeMessaging/host/native-messaging-example-host nativeMessaging/host/uninstall_host.sh
    2. 对于OS,您需要修复nativeMessaging/host/install_host.shnativeMessaging/host/uninstall_host.sh中的一些bug。有关修改后的脚本,请参阅下面。
    3. 对于OS,Linux和Windows遵循nativeMessaging/README.txt中的说明

  1. 运行Chrome扩展
    1. 在Chrome中,在地址栏中输入chrome://apps/
    2. 单击本机消息传递示例应用程序图标
    3. 在应用程序加载之后,您应该会看到一个名为“Connect”的按钮。单击该按钮,您将看到本机消息传递主机应用程序自动启动。

修正的

代码语言:javascript
运行
复制
#!/bin/sh
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

set -e

DIR="$( cd "$( dirname "$0" )" && pwd )"
if [ $(uname -s) == 'Darwin' ]; then
  if [ "$(whoami)" == "root" ]; then
    TARGET_DIR="/Library/Google/Chrome/NativeMessagingHosts"
  else
    TARGET_DIR="$HOME/Library/Application Support/Google/Chrome/NativeMessagingHosts"
  fi
else
  if [ "$(whoami)" == "root" ]; then
    TARGET_DIR="/etc/opt/chrome/native-messaging-hosts"
  else
    TARGET_DIR="$HOME/.config/google-chrome/NativeMessagingHosts"
  fi
fi

HOST_NAME=com.google.chrome.example.echo

# Create directory to store native messaging host.
mkdir -p "$TARGET_DIR"

# Copy native messaging host manifest.
cp "$DIR/$HOST_NAME.json" "$TARGET_DIR"

# Update host path in the manifest.
HOST_PATH="$DIR/native-messaging-example-host"
ESCAPED_HOST_PATH=${HOST_PATH////\\/}
sed -i -e "s/HOST_PATH/$ESCAPED_HOST_PATH/" "$TARGET_DIR/$HOST_NAME.json"

# Set permissions for the manifest so that all users can read it.
chmod o+r "$TARGET_DIR/$HOST_NAME.json"

echo Native messaging host $HOST_NAME has been installed.

修正的

代码语言:javascript
运行
复制
#!/bin/sh
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

set -e

if [ $(uname -s) == 'Darwin' ]; then
  if [ "$(whoami)" == "root" ]; then
    TARGET_DIR="/Library/Google/Chrome/NativeMessagingHosts"
  else
    TARGET_DIR="$HOME/Library/Application Support/Google/Chrome/NativeMessagingHosts"
  fi
else
  if [ "$(whoami)" == "root" ]; then
    TARGET_DIR="/etc/opt/chrome/native-messaging-hosts"
  else
    TARGET_DIR="$HOME/.config/google-chrome/NativeMessagingHosts"
  fi
fi

HOST_NAME=com.google.chrome.example.echo
rm "$TARGET_DIR/com.google.chrome.example.echo.json"
echo Native messaging host $HOST_NAME has been uninstalled.
票数 8
EN

Stack Overflow用户

发布于 2020-11-25 11:01:27

我想提供一个python 3版本的脚本,以取代本地消息传递-示例-主机。它是经过测试的Chrome v86和工作的预期。注意,python内核在tkinter窗口关闭时崩溃--这是因为线程内部的二进制数据交换导致线程被硬锁定(更多信息这里)。我添加了一个命令出口从chrome应用程序发送,以停止线程等待另一个stdin。收到后,python不会在出口处崩溃。

Python 3版本(用3.7.4测试):

代码语言:javascript
运行
复制
# A simple native messaging host. Shows a Tkinter dialog with incoming messages
# that also allows to send message back to the webapp.

import struct
import sys
import threading
import queue as Queue

try:
  import tkinter as Tkinter
  import tkinter.messagebox
except ImportError:
  Tkinter = None

# On Windows, the default I/O mode is O_TEXT. Set this to O_BINARY
# to avoid unwanted modifications of the input/output streams.
if sys.platform == "win32":
  import os, msvcrt
  msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
  msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

# Helper function that sends a message to the webapp.
def send_message(message):
   # Write message size.
  sys.stdout.buffer.write(struct.pack('I', len(message)))
  # Write the message itself.
  sys.stdout.write(message)
  sys.stdout.flush()

# Thread that reads messages from the webapp.
def read_thread_func(queue):
  message_number = 0
  while 1:
    # Read the message length (first 4 bytes).
    text_length_bytes = sys.stdin.buffer.read(4)

    if len(text_length_bytes) == 0:
      if queue:
        queue.put(None)
      sys.exit(0)

    # Unpack message length as 4 byte integer.
    text_length = struct.unpack('@I', text_length_bytes)[0]

    # Read the text (JSON object) of the message.
    text = sys.stdin.buffer.read(text_length).decode('utf-8')

    if text == '{"text":"exit"}':
      break

    if queue:
      queue.put(text)
    else:
      # In headless mode just send an echo message back.
      send_message('{"echo": %s}' % text)

if Tkinter:
  class NativeMessagingWindow(tkinter.Frame):
    def __init__(self, queue):
      self.queue = queue

      tkinter.Frame.__init__(self)
      self.pack()

      self.text = tkinter.Text(self)
      self.text.grid(row=0, column=0, padx=10, pady=10, columnspan=2)
      self.text.config(state=tkinter.DISABLED, height=10, width=40)

      self.messageContent = tkinter.StringVar()
      self.sendEntry = tkinter.Entry(self, textvariable=self.messageContent)
      self.sendEntry.grid(row=1, column=0, padx=10, pady=10)

      self.sendButton = tkinter.Button(self, text="Send", command=self.onSend)
      self.sendButton.grid(row=1, column=1, padx=10, pady=10)

      self.after(100, self.processMessages)

    def processMessages(self):
      while not self.queue.empty():
        message = self.queue.get_nowait()
        if message == None:
          self.quit()
          return
        self.log("Received %s" % message)

      self.after(100, self.processMessages)

    def onSend(self):
      text = '{"text": "' + self.messageContent.get() + '"}'
      self.log('Sending %s' % text)
      try:
        send_message(text)
      except IOError:
        tkinter.messagebox.showinfo('Native Messaging Example',
                              'Failed to send message.')
        sys.exit(1)

    def log(self, message):
      self.text.config(state=tkinter.NORMAL)
      self.text.insert(tkinter.END, message + "\n")
      self.text.config(state=tkinter.DISABLED)


def Main():
  if not Tkinter:
    send_message('"Tkinter python module wasn\'t found. Running in headless ' +
                 'mode. Please consider installing Tkinter."')
    read_thread_func(None)
    sys.exit(0)

  queue = Queue.Queue()

  main_window = NativeMessagingWindow(queue)
  main_window.master.title('Native Messaging Example')

  thread = threading.Thread(target=read_thread_func, args=(queue,))
  thread.daemon = True
  thread.start()

  main_window.mainloop()

  sys.exit(0)


if __name__ == '__main__':
  Main()

免责声明:我使用2至3实用程序进行最初的python3转换,我还采用了来自网络扩展 (火狐)版本的nativeMessage API示例的更改(它简化了,没有使用tkinter )。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23385991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档