如何将数据发送到Chrome扩展程序?

时间:2011-10-29 14:51:41

标签: javascript python google-app-engine google-chrome-extension

我正在为我的书签扩展程序开发用户身份验证。该扩展程序适用于http://ting-1.appspot.com/的Google App Engine(Python)后端。

首次展开广告时,background.html会在新标签页中打开options.html,然后用户输入其电子邮件地址。我将这样的电子邮件地址发送到应用程序(尚未尝试):

in options.html
---------------

var formData = new FormData();

formData.append("extension_user", userEmail);

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/authsender", true);
xhr.send(formData);

在应用中,处理程序AuthSender将确认电子邮件发送给用户:

class AuthSender(webapp.RequestHandler):
    def post(self):
        new_user = self.request.get("extension_user") 
        mail.send_mail(
        sender="Ting <ting@gmail.com>",
        to=new_user,
        subject="Ting Bookmarking: confirm your email",
        body="""click on the link below to confirm your email: 
<a href="http://ting-1.appspot.com/authHandler"></a> 

Happy Bookmarking!""")

如果用户点击应用中电子邮件AuthReceive处理程序中的链接,则会处理请求并向扩展程序发送确认。但我无法弄清楚如何将确认发送到扩展程序。

当用户点击链接时,如何将确认信息发送回分机?我是否再次使用XMLHttpRequest?怎么样?我需要在扩展名上放什么样的听众?

以下是应用中AuthReceive处理程序的草图:

class AuthReceive(InboundMailHandler):
    def receive(self, message):

#---------------------------------------
        #receive email // I know this part
        #send confirmation to extension // I need help with this
#--------------------------------------
...

在background.html中

//...
// add listener and save the variable to localStorage
//...

感谢您的帮助。

更新

这是符合Moishe's answer的代码。除最后一步外,一切正常:handler.onmessage未被触发。

options.html

<html>
<head><title>Extension Options</title></head>
<body>
<p>Enter your gmail address:</p>

<textarea id="getEmail" style="margin-bottom: 4px; width: 250px; height: 20px">
</textarea><br />

<button id="save">Save</button>
<!--<button id="save">Clear</button>-->

<script type="text/javascript">

document.getElementById("getEmail").placeholder = "your gmail address" ;

//send entered gmail address to the server
document.getElementById("save").addEventListener
(
    "click", 
    function ()
    {
        var userEmail = document.getElementById("getEmail").value;
        var formData = new FormData();
        formData.append("extension_user", userEmail);

        var channel;
        var socket;
        var handler = new Object();
        handler.onmessage =
        function (evt)
        {   
            //evt.data will be what the server sends in channel.send_message
            console.log("evt.data received from authhandler: " + evt.data);
        };    

        var xhr = new XMLHttpRequest();
        xhr.onReadyStateChange = function()
        {
            //error handling etc not included
            if (xhr.readyState == 4 && xhr.status == 200)
            {
                token = xhr.responseText;
                channel = new goog.appengine.Channel(token);
                socket = channel.open(handler);
            }
        };
        xhr.open("POST", "http://ting-1.appspot.com/authsender", true);
        xhr.send(formData);
        console.log("formData sent to authsender: " + formData);

    }, false
)
//...
</script>
</body>
</html>

AuthSender和AuthHandler

class AuthSender(webapp.RequestHandler):
    def post(self):
        new_user = self.request.get("extension_user")
        link = "http://ting-1.appspot.com/authhandler?new_user=%s" % new_user

        message = mail.EmailMessage()
        message.sender="Ting <ting@gmail.com>"
        message.to=new_user
        message.subject="Ting Bookmarking - Confirm your email"
        message.body="""Click on the link to confirm your email: %s """ % link
        message.send()

        logging.info("message sent to: %s " % message.to)

        token = channel.create_channel(new_user)
        self.response.out.write(token)

class AuthHandler(webapp.RequestHandler):
    def get(self):
        new_user = self.request.get("new_user")

        channel.send_message(new_user, new_user)

        logging.info("new_user sent to client: %s" % new_user)


工作版

Related question

options.html

<html>
<head>
    <title>Extension Options</title>
    <!-- this does not work because it is local url
    <script type="text/javascript" src="/_ah/channel/jsapi"></script>
    -->
    <script type="text/javascript" src="https://talkgadget.google.com/talkgadget/channel.js"></script>
</head>

<body>
<p>Enter your gmail address:</p>

<textarea id="getEmail" style="margin-bottom: 4px; width: 250px; height: 20px">
</textarea><br />

<button id="save">Save</button>

<script>
document.getElementById("getEmail").placeholder = "your gmail address" ;

document.getElementById("save").addEventListener
(
    "click", 
    function ()
    {
        var userEmail = document.getElementById("getEmail").value;
        var formData = new FormData();
        formData.append("extension_user", userEmail);

        var channel;
        var socket;
        var handler = 
        {
            onopen: function () { alert("onopen") },
            onerror: function () { alert("onerror") },
            onclose: function () { alert("onclose") },
            onmessage: 
            function (evt)
            {
                alert("evt.data is: " + evt.data)
            }
        };    

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function()
        {
            if (xhr.readyState == 4 && xhr.status == 200)
            {
                token = xhr.responseText;
                channel = new goog.appengine.Channel(token);
                socket = channel.open(handler);
            }
        };
        xhr.open("POST", "http://ting-1.appspot.com/authsender", true);
        xhr.send(formData);            
    }, false
)
</script>
</body>
</html>

AuthSender和AuthHandler

class AuthSender(webapp.RequestHandler):
    def post(self):
        new_user = self.request.get("extension_user")
        link = "http://ting-1.appspot.com/authhandler?new_user=%s" % new_user

        message = mail.EmailMessage()
        message.sender="Ting <ting@gmail.com>"
        message.to=new_user
        message.subject="Ting Bookmarking - Confirm your email"
        message.body="""Click on the link to confirm your email: %s """ % link
        message.send()

        token = channel.create_channel(new_user)

        self.response.out.write(token)

class AuthHandler(webapp.RequestHandler):
    def get(self):
        new_user = self.request.get("new_user")

        self.response.out.write(new_user)

        channel.send_message(new_user, new_user)

1 个答案:

答案 0 :(得分:4)

您可以使用Channel API来完成此操作。在创建XMLHttpRequest的同时请求令牌,并打开通道以侦听消息。当您的应用处理与用户点击链接相对应的HTTP请求时,请向为该用户扩展创建的频道发送消息。

更多细节:

基本上,在制作XHR的options.html中,执行以下操作:

var channel;
var socket;
var handler = {
  onmessage: function(evt) {
    // evt.data will be what your server sends in channel.send_message
  }
};
var xhr = new XMLHttpRequest();
xhr.onReadyStateChange = function() {
  // error handling and whatnot elided
  if (xhr.readyState == 4 and xhr.status == 200) {
    // We got a response from the server. The responseText is
    // a channel token so we can listen for a "verified" message.
    token = xhr.responseText;
    channel = new goog.appengine.Channel(token);
    socket = channel.open(handler);
  }
};
xhr.open("POST", "http://ting-1.appspot.com/authsender", true);
xhr.send(formData);

然后在您的服务器上,“authsender”页面的处理程序将执行以下操作:

class AuthSenderHandler(webapp.RequestHandler):
  def post(self):
    # get whatever data is in the form to send an email.
    # let's say that user_id is a field we extracted either from a cookie or from
    # the POST parameters themselves.
    link = "http://your.server.com/authHandler?user_id=%s" % user_id
    message = mail.EmailMessage()
    message.body = """some stuff %s""" % link
    # fill in other message fields, then send it.

    # now we'll create a channel token using the user_id and return 
    # it to the client.
    token = channel.create_channel(user_id)
    self.response.out.write(token)

以上两个功能将让您的客户在一个频道上收听。下一步是:当用户点击链接时会发生什么?

之前,我们在包含user_id参数的电子邮件中发送了该链接(出于说明的目的,您可能想要使用其他内容)。现在,当用户点击该链接时,它会向authHandler路径发出HTTP请求,其中user_id为参数。因此我们可以使用user_id来识别要发送消息的频道,如下所示:

class AuthHandler(webapp.RequestHandler):
  def get(self):
    user_id = self.request.get("user_id")
    # send a message indicating the user received the email and
    # verified to our client page. You may want to send other data.
    channel.send_message(user_id, "authorized")
    # probably want to show a nice "you've been authorized" page or something

然后将调用handler.onmessage回调,您可以执行用户验证其电子邮件地址所需的任何操作。

希望有所帮助!