Skip to content

Commit

Permalink
Revert to ae1c217
Browse files Browse the repository at this point in the history
  • Loading branch information
guest271314 authored May 2, 2022
1 parent 95b9d16 commit b41c86e
Showing 1 changed file with 31 additions and 12 deletions.
43 changes: 31 additions & 12 deletions native-messaging/app/ping_pong.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
#!/usr/bin/env -S python3 -u
# https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging
# https://github.com/mdn/webextensions-examples/pull/157
# Note that running python with the `-u` flag is required on Windows,
# in order to ensure that stdin and stdout are opened in binary, rather
# than text, mode.
#!/usr/bin/env python

import sys
import json
Expand All @@ -18,7 +13,7 @@ def getMessage():
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.buffer.read(messageLength).decode('utf-8')
return json.loads(message)["message"]
return json.loads(message)

# Encode a message for transmission,
# given its content.
Expand All @@ -36,8 +31,32 @@ def sendMessage(encodedMessage):
while True:
receivedMessage = getMessage()
if receivedMessage == "ping":
sendMessage(encodeMessage({"message":"pong3"}))
except Exception as e:
sys.stdout.buffer.flush()
sys.stdin.buffer.flush()
sys.exit(0)
sendMessage(encodeMessage("pong3"))
except AttributeError:
# Python 2.x version (if sys.stdin.buffer is not defined)
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
return json.loads(message)

# Encode a message for transmission,
# given its content.
def encodeMessage(messageContent):
encodedContent = json.dumps(messageContent)
encodedLength = struct.pack('@I', len(encodedContent))
return {'length': encodedLength, 'content': encodedContent}

# Send an encoded message to stdout
def sendMessage(encodedMessage):
sys.stdout.write(encodedMessage['length'])
sys.stdout.write(encodedMessage['content'])
sys.stdout.flush()

while True:
receivedMessage = getMessage()
if receivedMessage == "ping":
sendMessage(encodeMessage("pong2"))

0 comments on commit b41c86e

Please sign in to comment.