天天看點

webkit的js對象擴充(一)——binding方式建立自定義對象(單執行個體)

轉載請注明出處:http://blog.csdn.net/cxf8804

第一份工作的第一個任務,老大讓我搞懂webkit的js對象擴充。小弟不才,第一次接觸webkit,這兩天請教了前輩,總算建立了自己的對象,輸出了“Hello World!”。現在跟大家分享下。

通過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
           

2.添加MyObject.cpp檔案

#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!";
	}
}
           

3.添加MyObject.idl檔案

module window {
	interface MyObject {
		readonly attribute DOMString description;
	};
}
           

4.修改DOMWindow.h檔案

這裡還需要在開始添加: 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;
           

6.修改DOMWindow.idl檔案

添加:

attribute [Replaceable] MyObject MyObject;
           

7.修改CMakeLists.txt

将MyObject.cpp、MyObject.idl加入編譯。

OK。以上步驟就添加了一個自定義的全局對象。這是單執行個體的,有時間了再把多執行個體的過程寫下,也就是可以new了。

小弟新手,有問題請大家多多指教。