跨浏览器扩展的jQuery访问。图层 [英] jQuery Access Across Chrome Ext. Layers

查看:106
本文介绍了跨浏览器扩展的jQuery访问。图层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery开发Chrome扩展程序时,我遇到了一个特别奇怪的问题。我的扩展中有两个框架,弹出页面和背景页面。这两个页面都包含了jQuery库。基本上我想要做的是,当用户点击浏览器动作图标时,显示一个加载屏幕,同时背景页面收集数据,然后将其发送回弹出页面。我试图通过弹出页面在后台页面调用一个函数来做到这一点,然后让后台页面使用弹出窗口的dom访问数据并在UI中显示。不过,我注意到,当你从chrome.extension.getView()返回一个Window对象时,出于某种原因它没有访问jQuery库的权限。任何对'$'的调用都会遇到'找不到方法'的错误。那么处理这个问题最好的办法是什么?

I'm having a particularly odd issue when developing Chrome extensions using jQuery. I have two "frames" in my extension, the popup page and the background page. Both of these pages have included within them the jQuery library. Essentially what I would like to do is when the user clicks on the browser action icon a loading screen is shown while the background page gathers the data and then sends it back to the popup page. I've tried to do this by having the popup page call a function in the background page and then have the background page use the popup window's dom to access the data and show in the UI. However, I'm noticing that when you get a Window object back from chrome.extension.getView() it does not have access to the jQuery library for some reason. Any call to '$' is met with a 'method not found' error. So what would be the best way to handle this?

推荐答案

我会使用消息解析。从本质上讲,你可以在你的后台页面中添加一个监听器函数,类似于这个:(从文档页面中稍微简化了一些例子)

I would do this using message parsing. Essentially, you add a listener function in your background page, similar to this: (slightly simplified example from the documentation page)

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) 
    {
        console.log("Received a request!");
        if (request.message == "hello")
            sendResponse({message: "goodbye"});
    });

后台页面提取信息,并使用sendResponse函数将其返回给弹出窗口。

The background page fetches the information, and returns it to the popup using the sendResponse function.

然后在弹出窗口中,执行如下所示的内容:

Then in your popup, you implement something like this:

chrome.extension.sendRequest({message: "hello"}, function(response) {
    console.log(response.message);
});

消息( {message:hello} 部分)可以是任何兼容JSON的对象。

Messages (the {message: "hello"} parts) can be any JSON compatible object.

这篇关于跨浏览器扩展的jQuery访问。图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆