Seems to work like this:
global.html
Code:
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script type="text/javascript" charset="utf-8">
safari.application.addEventListener("command", performCommand, false);
function performCommand(event) {
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("name", "data");
}
</script>
</head>
<body>
</body>
</html>
injected.js
Code:
function handleMessage(event) {
var range = window.getSelection().getRangeAt(0);
var selectionParentText = range.startContainer.textContent;
range.startContainer.textContent = selectionParentText.substring(0,range.startOffset) + "[b]" + range.toString() + "[/b]" + selectionParentText.substring(range.endOffset,selectionParentText.length);
}
safari.self.addEventListener("message", handleMessage, false);
This code doesn't check the event.command value, or the messageEvent.name value, both of which should probably be employed to differentiate behaviors based on input.