通过binding方式
要扩展一个全局JS对象除了要为webkit添加这个对象的头文件和cpp文件外,还需要为这个对象写一个idl文件以便webkit自动生成相应的代码;另外,还需要修改DOMWindow.*以便把新对象注册上去。下面以MyObject对象为例介绍具体步骤。
WebCore/page/
1.添加MyObject.h文件
- #ifndef MyObject_h
- #define MyObject_h
- #include <wtf/PassRefPtr.h>
- #include <wtf/RefCounted.h>
- #include <wtf/RefPtr.h>
- namespace WebCore {
- class Frame;
- class String;
- class MyObject : public RefCounted<MyObject> {
- public:
- static PassRefPtr<MyObject> create(Frame* frame)
- {
- return adoptRef(new MyObject(frame));
- }
- ~MyObject();
- void disconnectFrame();
- Frame* frame() const { return m_frame; }
- String description() const;
- private:
- MyObject(Frame*);
- Frame* m_frame;
- };
- }
- #endif
- #include "MyObject.h"
- #include "PlatformString.h"
- namespace WebCore {
- MyObject::MyObject(Frame* frame)
- : m_frame(frame)
- {
- }
- MyObject::~MyObject()
- {
- disconnectFrame();
- }
- void MyObject::disconnectFrame()
- {
- m_frame = 0;
- }
- String MyObject::description() const //对象的属性
- {
- return "Hello World!";
- }
- }
- module window {
- interface MyObject {
- readonly attribute DOMString description;
- };
- }
添加如下声明:
- public:
- MyObject* myObject() const;
- MyObject* optionalMyObject() const { return m_myObject.get(); }
- private:
- mutable RefPtr<MyObject> m_myObject;
添加接口实现
- MyObject* DOMWindow::myObject() const
- {
- if (!m_myObject)
- m_myObject = MyObject::create(m_frame);
- return m_myObject.get();
- }
void DOMWindow::clear()函数中添加:
- if (m_myObject)
- m_myObject->disconnectFrame();
- m_myObject = 0;
添加:
- attribute [Replaceable] MyObject MyObject;
7.修改CMakeLists.txt
将MyObject.cpp、MyObject.idl加入编译。
OK。以上步骤就添加了一个自定义的全局对象。这是单实例的,有时间了再把多实例的过程写下,也就是可以new了。
小弟新手,有问题请大家多多指教。
转自http://blog.youkuaiyun.com/perfectpdl/article/details/7051129