IS it possible to access web content direc开发者_如何学JAVAtly from the (Safari) toolbar? I can now access it from a contextmenu, but no idea how i get the same functionaliy to a toolbar.
This is what i got:
// injected
document.addEventListener("contextmenu", handleMessage, false);
function handleMessage(msgEvent) {
var sel = '';
sel = window.parent.getSelection()+'';
safari.self.tab.setContextMenuEventUserInfo(msgEvent, sel);
}
// global
safari.application .addEventListener("command", performCommand, false);
function performCommand(event) {
console.log('performCommand');
if (event.command == "abc") {
var query = event.userInfo;
console.log(query);
alert(query);
}
}
But how do i this content directly from the toolbar ??
OK, basically it works like this:
- in global the performCommand get called (by clicking on the toolbar), dispatching a event
- this event is caught in handleGextText
- in handleGextText, you do what you need to do and call safari.self.tab.dispatchMessage this dispatches a event back to global
- in global you the event get caught by handleEvent
>
// Global Script
safari.application.addEventListener("command", performCommand, false);
safari.application.addEventListener("message", handleEvent, false);
// send message
function performCommand(event) {
console.log('command:' + event.command);
if (event.command == "abc") {
console.log("msg: my message");
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("msg", "do-something");
}
}
function handleEvent(event) {
var messageName = event.name;
console.log("evenname:" + event.name);
if (messageName === "did-something") {
var msg = event.message;
// do something
}
}
// Injected Script
if (window.top === window) { // inject only once!
console.log("add event listners [injected.js]");
safari.self.addEventListener("message", handleGextText, false);
}
function handleGextText(event) {
console.log("evenname:" + event.name);
console.log("evenmsg :" + event.message);
var messageName = event.name;
var messageData = event.message;
if (messageName === "msg") {
if (messageData === "do-something") {
console.log('msg received: ' + event.name);
var sel = '';
// do what you need to do and dispatch message back to Global
console.log("send message to toolbar");
safari.self.tab.dispatchMessage("did-something", sel);
}
}
}
OK, well found it. I solved it with messages.
I send in 'global' a message, which is catches by the injected script. That function get the selected text (puts it in userinfo), and sends a message back to global.
Thats it.
精彩评论