简体   繁体   English

从Python干净地调用Webkit Javascript函数

[英]Invoke Webkit Javascript Functions from Python Cleanly

For an application I am currently working on I decided to use HTML5 for the interface, allowing me to have a modern interface that doesn't change in appearance when you change operating systems. 对于当前正在开发的应用程序,我决定将HTML5用于该界面,从而使我拥有一个现代的界面,该界面在您更改操作系统时不会改变。 Naturally I chose the webkit engine for rendering, specifically the PyQT bindings. 我自然选择了Webkit引擎进行渲染,特别是PyQT绑定。 My issue is that every time I want to call a javascript function from python, I have to do it using the messy evaluateJavaScript function. 我的问题是,每次我想从python调用javascript函数时,都必须使用凌乱的validateJavaScript函数来实现。

Any alternatives I can use that allow a more direct way of calling javascript functions? 我可以使用其他替代方法来允许更直接的方式来调用javascript函数吗?

PyQt doesn't have any wrapper that makes things easier. PyQt没有使事情变得更容易的包装器。

You could write your own, if you want—not perfect, but a little nicer. 如果需要,您可以编写自己的文件-不够完美,但是要好一些。 For example, something like this (just a skeleton, not actual code): 例如,如下所示(只是一个框架,不是实际的代码):

class JSObject(object):
    def __init__(self, name):
        self.name = name
    def __getattr__(self, attr):
        class Proxy(object):
            def __init__(self, objname, funcname):
                self.name = '%s.%s' % (objname, funcname)
            def __call__(self, *args):
                argstr = ', '.join(json.dumps(arg) for arg in args)
                retstr = evaluateJavaScript('%s(%s)' % (self.name, argstr)
                # realistically you may want to do more to parse the return
                # value—e.g., look up/create JSONObjects as needed?
                return json.loads(retstr)
        return Proxy(self, attr)

thingIWantToCall = JSObject('thingIWantToCall')
print thingIWantToCall.methodIWantToCallOnIt('foo', [1, 2, 3])

As you can see, it's still a bit clumsy—you have to manually create the object proxies, and there's no way to call free functions or declare variables or anything other than call methods on objects. 如您所见,它仍然有些笨拙-您必须手动创建对象代理,并且无法调用自由函数或声明变量或除对象上的调用方法以外的任何方法。 Some of that could be implemented, but there's a limit to how far you can go. 其中一些可以实现,但是可以走多远。 (Of course you can always fall back to explicit strings.) (当然,您始终可以使用显式字符串。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM