Skip to content

Instantly share code, notes, and snippets.

@rschroll
Created July 10, 2014 18:30
Show Gist options
  • Save rschroll/5406e95d8b008736852c to your computer and use it in GitHub Desktop.
Save rschroll/5406e95d8b008736852c to your computer and use it in GitHub Desktop.
Communicating with an Oxide WebView
<html>
<head>
<script>
document.addEventListener("QMLmessage", function (event) {
document.body.innerHTML += "<p>Message received. You said " + event.detail.greeting + "</p>";
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
import QtQuick 2.0
import Ubuntu.Components 0.1
import com.canonical.Oxide 1.0
//import Ubuntu.Components.Extras.Browser 0.2
Rectangle {
width: units.gu(50)
height: units.gu(75)
// Both the UserScript and the call to sendMessage need to share the same
// context, which should be in the form of a URL. It doesn't seem to matter
// what it is, though.
property string usContext: "messaging://"
WebView {
id: webview
anchors {
top: parent.top
left: parent.left
right: parent.right
bottom: button.top
}
context: webcontext
url: Qt.resolvedUrl("oxide-test.html")
}
WebContext {
id: webcontext
userScripts: [
UserScript {
context: usContext
url: Qt.resolvedUrl("oxide-user.js")
}
]
}
Button {
id: button
anchors {
bottom: parent.bottom
left: parent.left
right: parent.right
}
text: "Press Me"
onClicked: {
var req = webview.rootFrame.sendMessage(usContext, "MESSAGE", {greeting: "Hello"})
req.onreply = function (msg) {
console.log("Got reply: " + msg.str);
}
req.onerror = function (code, explanation) {
console.log("Error " + code + ": " + explanation)
}
}
}
}
oxide.addMessageHandler("MESSAGE", function (msg) {
var event = new CustomEvent("QMLmessage", {detail: msg.args});
document.dispatchEvent(event);
msg.reply({str: "OK"});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment