Chrome 扩展:内容脚本 ->动态功能
我想在内容脚本(Chrome 扩展)上调用动态函数。但常见的方法不起作用:
chrome.extension.onRequest.addListener(function cs_listener(request, sender, sendResponse) {
[request.action]();
}
request.action 是废话。其中函数 blah() 是一个....现在它来了...一个函数!
抛出错误:
Error in event handler for 'undefined': TypeError: object is not a function
有人解决了这个问题吗?我真的不喜欢为我需要的每一个动作进行切换。
I would like to call a dynamic function on a Content Script (Chrome Extension). But the common way doesn't work:
chrome.extension.onRequest.addListener(function cs_listener(request, sender, sendResponse) {
[request.action]();
}
request.action is blah. Where function blah() is a....and now it comes...a function!
Error thrown:
Error in event handler for 'undefined': TypeError: object is not a function
Someone got over this? I really don't like to make a switch for every action I need.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须使用
as
创建一个包含 request.action 的数组,并尝试调用它,这会导致错误。
window[request.action]();
从window
获取名为request.action
的属性并调用它。您可能还想首先检查该属性是否已定义:
You have to use
as
creates an array containing
request.action
, and tries to call that, which results in the error.window[request.action]();
gets the property namedrequest.action
fromwindow
and calls that.You also might want to check if the property is defined first:
另一种方法是仅从后台页面调用该函数,而不发送请求:
Another way would be just calling that function from a background page, without sending a request: