Created
July 10, 2014 18:30
-
-
Save rschroll/5406e95d8b008736852c to your computer and use it in GitHub Desktop.
Communicating with an Oxide WebView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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