Search code examples
javascriptqtembedded-resourceqwebkit

QT and QwebKit can i load javascript file as resource file and use it?


I wonder if I can load Javascript as a resource file to use in QwebKit? Well, it doesn't have to be resource file, I am just looking for a method to embed JS files into my application.


Solution

  • Yes, you can. I do this in my app. For example:

    QWebFrame* frame = ui->webView->page()->mainFrame();
    frame->evaluateJavaScript(readFile(":/scripts/foo.js"));
    

    Where readFile is a function which reads the contents of a file to a string. For example:

    QString readFile (const QString& filename)
    {
        QFile file(filename);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream stream(&file);
            return stream.readAll();
        }
        return "";
    }
    

    Since the filename starts with :, it is read from the resource file. The resource file must have /scripts/foo.js defined, obviously.