为什么chrome.runtime未定义? [英] Why is chrome.runtime undefined?

查看:1296
本文介绍了为什么chrome.runtime未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建Google Chrome浏览器扩展程序(我的第一个扩展程序),并且希望将扩展程序的消息发送到当前选项卡。

我正在遵循以下文档:

https://开发者。 chrome.com/apps/runtime#event-onMessage



该扩展将一个小的外部JS加载到选项卡的HTML中,该HTML包含以下代码:

  chrome.runtime.onMessage.addListener(
函数(request,sender,sendResponse){
console.log (请求)
}
);

一旦JS被加载,我会得到以下错误:

Uncaught TypeError:无法读取undefined 的属性'onMessage'。

打开控制台和键入 chrome ,我可以看到运行时不是 chrome 的属性。



看起来我做错了什么,但是什么?是否需要向 manifest.json 文件添加内容?



Chrome版本39.0.2171.71米

>

谢谢。

解决方案

$ b

有时这是可取的:这是唯一的方法访问页面级JavaScript对象。



但就你而言,这意味着代码无法访问Chrome API,因为它与页面的代码相同 。



您需要查看页面级和上下文脚本,或(扰流器,在大多数情况下需要上下文脚本代理)。

I am creating a Google Chrome extension (my first one) and I want to send messages from the extension to the current tab.

I am following the documentation:

https://developer.chrome.com/apps/runtime#event-onMessage

The extension loads a small external JS into the tab's HTML, which contains the following code:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(request)
    }
);

As soon as the JS is loaded I get the following error:

Uncaught TypeError: Cannot read property 'onMessage' of undefined.

Opening console and typing chrome, I can see that the runtime is not a property of chrome.

It looks like I am doing something wrong, but what? Do I need to add something to the manifest.json file?

Chrome Version 39.0.2171.71 m

Thank you.

解决方案

If you're inserting JavaScript into a page with a <script> tag, it executes in the page's context.

Sometimes it is desirable: that's the only way to access page-level JavaScript objects.

But in your case it means that the code does not have access to Chrome APIs, as it is "the same" as the page's code.

You need to look into communicating between page-level and context scripts, or between page-level and background (spoiler, in most cases needs a context script proxy anyway).

这篇关于为什么chrome.runtime未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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