1

I am trying to call a Javascript function from Qt. My HTML page looks like this,

<html>
<body>
<script type="text/javascript">
 myoperations.submit();

function test(){
  return "Called me!";
 }
 </script>

</body>
</html>

Here is my Qt file

 /.. all necessary include ../ 
 class MyJavaScriptOperations : public QObject {
   Q_OBJECT
   public:
    MyJavaScriptOperations(){

      qDebug() << "In constructor";
    }

 public slots:
   Q_INVOKABLE
  void submit()
   {
    QWebView *view2 = new QWebView();
    view2->resize(400,500);
    QVariant f1result = view2->page()->mainFrame()->evaluateJavaScript("test()");
    qDebug() << f1result.toString();
    view2->show();
   }
};


 int main(int argc, char *argv[])
 {
  QApplication a(argc, argv); 

   QWebView *view = new QWebView();
   view->resize(400, 500);
   view->page()->mainFrame()->addToJavaScriptWindowObject("myoperations", new MyJavaScriptOperations);
   view->load(QUrl("file:///C:/programs/test.html"));
   view->show();
   return a.exec();
 }

#include "main.moc"

In the console I get f1result to be "" (an empty string). Why isn't it showing the returned value?

Can someone help me in this?

1 Answer 1

3

You're creating a second QWebView inside submit() instead of using the one where your object was added to. Here's a fixed version of your code:

QWebView *view;
class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
    MyJavaScriptOperations(){
        qDebug() << "In constructor";
    }

    Q_INVOKABLE void submit()
    {
        QVariant f1result = view->page()->mainFrame()->evaluateJavaScript("test()");
        qDebug() << f1result.toString();
    }
};


int main(int argc, char *argv[])
{
    QApplication a(argc, argv); 

    view = new QWebView;
    view->resize(400, 500);
    view->page()->mainFrame()->addToJavaScriptWindowObject("myoperations", new MyJavaScriptOperations);
    view->load(QUrl("file:///tmp/o/index.html"));
    view->show();
    return a.exec();
}

#include "main.moc"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.