expose cpp objects javascript qt

expose cpp objects javascript qt

Following class design should help in exposing a object from C++ to JavaScript and calling this object functions from java script.

Browser.h

class CacheManager: public QObject {
Q_OBJECT
public:
CacheManager(CBrowser *browser);

public slots:
public slots:
QString setCacheSize();
private:
CBrowser *m_browser;
};
class CBrowser: public QObject {

Q_OBJECT

public:
CacheManager m_CacheManager;
/*Constructor*/
CBrowser();

/*Destructor*/
~CBrowser();

/*Function to set the webview for a application*/
void setWebView(CWindowRenderer *f_pView, const ulong f_culAppID);

/*Web View*/
CWindowRenderer *m_pView;
/*Web Frame*/
QWebFrame *m_pFrame;
};
WindowRenderer.h
class CWindowRenderer: public QObject
{
Q_OBJECT

public:
QWebPage *page() const;
};

Browser.cpp

void CBrowser::setWebView(CWindowRenderer *f_pView,const ulong f_culAppID)
{
FUNC_ENTERED;
m_iCurrAppID = f_culAppID;

if(NULL!=f_pView)
{
QWebPage *l_pPage = f_pView->page();

if(NULL!=l_pPage)
{
m_pFrame = l_pPage->mainFrame();

if(NULL!=m_pFrame)
{
/*Function call to add the CBrowser object to javascript window object.*/
addObject();

m_pView = f_pView;
/*Associating the web frame object to the windowobjectCleared signal*/
connect( m_pFrame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addObject()) );

}
else
{
// print error
}
}
else
{
// print error
}
}
else
{
//print error
}
}
CBrowser::CBrowser(): m_CacheManager(this)
{
FUNC_ENTERED;

setObjectName(QString(“global”));

}

void CBrowser::addObject()
{

m_CacheManager.setParent(this);
m_CacheManager.setObjectName(QString(“cachemanager”));
if(m_pFrame) {
m_pFrame->addToJavaScriptWindowObject( “global”, this);
QFile file(“apps.js”);
if(file.open(QIODevice::ReadOnly))
{
QByteArray data = file.readAll();
QString str(data);
m_pFrame->evaluateJavaScript(str);
}
else
{
//error
}
}

}

apps.js
if(typeof(global.cachemanager) !== “object”)
global.cachemanager = new Object();

//Now call any function with
global.cachemanager.setCacheSize()

Dynamically include js script on a webpage

var script_tag = document.createElement(‘script’);
script_tag.setAttribute(“type”, “text/javascript”);
script_tag.setAttribute(“src”, “https://yourdomain.com//test.js”);
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName(“head”)[0] || document.documentElement).appendChild(script_tag);

Leave a Reply

Your email address will not be published. Required fields are marked *