WebKit的JavaScript对象扩展
转载时请注明出处和作者联系方式: http://mogoweb.net mogoweb@gmail.com
本文的内容主要参考网上收集的资料,不过在Android 4.0 webkit上做扩展时,碰到一些问题,觉得有必要记录下来。
所谓扩展JavaScript对象,就是增加一个JS对象,但它并没有定义在标准的JS对象集合中。如果网页中包含了扩展的JS对象,使用普通的浏览器就会报JS错误。
下面以添加HelloObject对象为例说明具体步骤,该对象具有description属性:
1. 添加HelloObject.h, HelloObject.cpp, HelloObject.idl文件,简单起见,将这三个文件放到Source/WebCore/page目录下。
#ifndef HelloObject_h
#define HelloObject_h#include <wtf/PassRefPtr.h>
#include <wtf/RefCounted.h>#include "PlatformString.h"
namespace WebCore {
class HelloObject : public RefCounted<HelloObject> {
public:
static PassRefPtr<HelloObject> create() { return adoptRef(new HelloObject()); }String description() const;
private:
HelloObject();
};} // namespace WebCore
#endif // HelloObject_h
HelloObject.h
#include "config.h"
#include "HelloObject.h"namespace WebCore {
HelloObject::HelloObject()
{
}String HelloObject::description() const
{
return "Hello Object";
}} // namespace WebCore
HelloObject.cpp
module window {
interface [OmitConstructor] HelloObject {
readonly attribute DOMString description;
};}
HelloObject.idl
2. 修改Source/WebCore/page/下的DOMWindow.h文件,添加如下声明:
class HelloObject;
…
public:
HelloObject* helloObject() const;
HelloObject* optionalHelloObject() const { return m_helloObject.get(); }
private:
mutable RefPtr<HelloObject> m_helloObject;
3. 修改Source/WebCore/page/下的DOMWindow.cpp文件,添加接口实现:
HelloObject* DOMWindow::helloObject() const
{
if (!m_helloObject)
m_helloObject = HelloObject::create();
return m_helloObject.get();
}在DOMWindow::clear()函数中添加一行语句:
m_helloObject = 0;
4. 修改DOMWindow.idl文件,添加:
attribute [Replaceable] HelloObject helloObject;
5. 接下来需要修改编译系统,让android编译系统编译新增的文件:
首先修改Source/WebCore/Android.mk,增加page/HelloObject.cpp到LOCAL_SRC_FILES变量,其次需要修改Source/WebCore/Android.derived.v8bindings.mk,增加$(intermediates)/bindings/V8HelloObject.h到GEN变量。(注:这个是必须的,否则就不会根据HelloObject.idl生成V8HelloObject.h文件,在编译时会出错,这也是折腾了半天得出的成果)
至此,工作基本上完成,待webkit重新编译后,可以用如下的网页进行验证:
<html>
<body>
<script type="text/javascript">
document.write("<p> This is from HelloObject: ");
document.write(helloObject.description + "</p>");
</script>
</body>
</html>