通过binding方式
要扩展一个全局JS对象除了要为webkit添加这个对象的头文件和cpp文件外,还需要为这个对象写一个idl文件以便webkit自动生成相应的代码;另外,还需要修改DOMWindow.*以便把新对象注册上去。下面以MyObject对象为例介绍具体步骤。
修改了一点点,其实大家可以参看webkit里面已经实现的Navigator对象。
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;
- };
- }
这里还需要在开始添加: class MyObject;
添加如下声
明:
- public:
- MyObject* myObject() const;
- MyObject* optionalMyObject() const { return m_myObject.get(); }
- private:
- mutable RefPtr<MyObject> m_myObject;
5.修改DOMWindow.cpp文件
这里也要加上头文件:#include "MyObject.h"
添加接口实现
- 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加入编译。