I'm having a problem where my dynamically generated html is getting escaped and outputed on the screen. heres what I have:
#{
string TrialMessage = string.Empty;
if ((bool)ViewBag.msd.IsOnTrial == true)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var daysToTrialExpiation = expDate.AddDays(1) - System.DateTime.UtcNow;
TrialMessage = "<b>Trial Ends in: <span style=\"color:[Color];\">" + (daysToTrialExpiation.Days) + "</span> Days</b>";
if (daysToTrialExpiation.Days > 5)
{
TrialMessage = TrialMessage.Replace("[Color]", "green");
}
else if (daysToTrialExpiation.Days > 2)
{
TrialMessage = TrialMessage.Replace("[Color]", "orange");
}
else if (daysToTrialExpiation.Days > 0)
{
TrialMessage = TrialMessage.Replace("[Color]", "red");
}
else
{
TrialMessage = "<b style=\"color: red;\"> Trial Ended " + Math.Abs(daysToTrialExpiation.Days) + " Days Ago</b>";
}
}
}
When I use the TrialMessage in the View, I'm getting the escaped version of it outputted on the screen:
<b>Trial Ends in: <span style="color:green;">15</span> Days</b>
I have tried to use Html.Raw(TrialMessage) I've even tried to manually create an HTMLString with the same result. What am I missing?
Update: The way I'm outputting it on the view is:
#Html.Raw(TrialMessage)
In an effort to just get it working (it seems you're pressed for time) what if you removed html from the variable?
Perhaps something like this could work for you:
#{
string trialColor = string.Empty;
int trialDays = 0;
if ((bool)ViewBag.msd.IsOnTrial)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var trialDays = (expDate.AddDays(1) - System.DateTime.UtcNow).Days;
if (trialDays > 5)
{
trialColor = "green";
}
else if (trialDays > 2)
{
trialColor = "orange";
}
else
{
trialColor = "red";
}
}
}
...
#if((bool)ViewBag.msd.IsOnTrial && trialDays > 0)
{
<strong>Trial Ends in: <span style="color:#trialColor;">#trialDays </span> Days</strong>
} else if((bool)ViewBag.msd.IsOnTrial) {
<strong style="color: red;">Trial Ended #Math.Abs(trialDays) Days Ago</strong>
}
Note: untested code. It's been a bit since I've written razor.
Related
While a Field Code has more than 40 characters then OpenXML does not replace FieldCode with result values also Formating is not getting applied for the same. The below is working fine filed codes which have up to 40 characters but failed for more than 40 characters.
var format = "";
foreach (var paragraph in wordDocument.MainDocumentPart.RootElement.Descendants())
{
foreach (FieldCode fieldCode in paragraph.Descendants())
{
if (!String.IsNullOrEmpty(fieldCode.InnerText) && fieldCode.InnerText.Trim() != null && fieldCode.InnerText.Trim() != ""
&& (fieldCode.InnerText.Contains('#') || fieldCode.InnerText.Contains('#')))
{
if (fieldCode.InnerText.Contains('#'))
{
var indexofsymbol = fieldCode.InnerText.IndexOf('#') + 1;
format = fieldCode.InnerText.Substring(indexofsymbol, fieldCode.InnerText.Length - indexofsymbol);
}
else if (fieldCode.InnerText.Contains('#'))
{
var indexofsymbol = fieldCode.InnerText.IndexOf('#') + 1;
format = fieldCode.InnerText.Substring(indexofsymbol, fieldCode.InnerText.Length - indexofsymbol);
}
Run xxxfield = (Run)fieldCode.Parent;
Run rBegin = xxxfield.PreviousSibling<Run>();
Run rSep = xxxfield.NextSibling<Run>();
Run rText = rSep.NextSibling<Run>();
Run rEnd = rText.NextSibling<Run>();
if (null != xxxfield)
{
Text t = rEnd.GetFirstChild<Text>();
t = xxxfield.Descendants<Text>().FirstOrDefault();
if (t == null)
t = rText.GetFirstChild<Text>();
if (t != null)
{
var fieldName = t.Text.ToString().Substring(1, t.Text.Length - 2);
if (mergeFields.TryGetValue(fieldName, out dictValue))
{
if (fieldCode.InnerText.Contains('#'))
{
DateTime date = DateTime.Parse(dictValue);
t.Text = date.ToString(format); //Convert.ToDateTime(dictValue).ToString(format);
}
else if (fieldCode.InnerText.Contains('#'))
{
t.Text = Convert.ToDouble(dictValue).ToString(format);
}
}
}
}
}
}
}
I'm doing a custom validation for an ISBN number, I already have the function that checks the number and works perfect giving me the response by console, but I need to do the custom validator to get the error in the view with the form control and in this step this error is showing in console when I write an ISBN number, It's like it checks the errors but it doesn't know when its right and it should take the null response as a right ISBN number, at least thats what I saw in some examples.
core.js:6210 ERROR TypeError: Cannot read properties of null (reading 'CheckDigit')
at LibrosComponent_Template (libros.component.html:22)
at executeTemplate (core.js:9600)
at refreshView (core.js:9466)
at refreshComponent (core.js:10637)
at refreshChildComponents (core.js:9263)
at refreshView (core.js:9516)
at refreshEmbeddedViews (core.js:10591)
at refreshView (core.js:9490)
at refreshComponent (core.js:10637)
at refreshChildComponents (core.js:9263)
This is my typescript,
export class LibrosComponent implements OnInit {
//ISBN Validator
isbnValue: string = ""
firstFormGroup: FormGroup;
secondFormGroup: FormGroup;
constructor(
private _formBuilder: FormBuilder,
) {}
ngOnInit() {
this.firstFormGroup = this._formBuilder.group({
tituloControl: ['', Validators.required],
isbnControl: ['', Validators.required],
},
{ validator: this.isbnValidate });
}
isbnValidate(g: FormGroup) {
var isbnValue = g.get('isbnControl').value
var subject = isbnValue;
// Checks for ISBN-10 or ISBN-13 format
var regex = /^(?:ISBN(?:-1[03])?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]$/;
if (regex.test(subject)) {
// Remove non ISBN digits, then split into an array
var chars = subject.replace(/[- ]|^ISBN(?:-1[03])?:?/g, "").split("");
// Remove the final ISBN digit from `chars`, and assign it to `last`
var last = chars.pop();
var sum = 0;
var check, i;
if (chars.length == 9) {
// Compute the ISBN-10 check digit
chars.reverse();
for (i = 0; i < chars.length; i++) {
sum += (i + 2) * parseInt(chars[i], 10);
}
check = 11 - (sum % 11);
if (check == 10) {
check = "X";
} else if (check == 11) {
check = "0";
}
} else {
// Compute the ISBN-13 check digit
for (i = 0; i < chars.length; i++) {
sum += (i % 2 * 2 + 1) * parseInt(chars[i], 10);
}
check = 10 - (sum % 10);
if (check == 10) {
check = "0";
}
}
if (check != last) {
return null;
} else {
return g.get('isbnControl').setErrors( {CheckDigit: true} )
}
} else {
return g.get('isbnControl').setErrors( {Invalid: true} );
}
}
}
In my HTML I have some inputs that are included in the form:
<form class="form" [formGroup]="firstFormGroup">
<div class="container-1">
<mat-form-field class="width">
<mat-label>TÃtulo</mat-label>
<input matInput formControlName="tituloControl" required>
</mat-form-field>
<mat-form-field class="width">
<mat-label>ISBN</mat-label>
<input matInput formControlName="isbnControl" required>
<mat-error *ngIf="firstFormGroup.controls['isbnControl'].pristine || firstFormGroup.controls.isbnControl.errors['CheckDigit']">Invalid ISBN check digit</mat-error>
<mat-error *ngIf="firstFormGroup.controls['isbnControl'].pristine || firstFormGroup.controls.isbnControl.errors['Invalid']">Invalid ISBN</mat-error>
</mat-form-field>
</form>
I already found the solution to the error, replacing the .errors [''] with hasError (''), the .errors[] is to read the property of the object that contains the validation error. But first I have to evaluate with the hasError () method if that property exists to access it.
My work uses a proprietary system to store medical records. The site is coded in javascript, and we are unable to change the coding of the site. We would like to use iPads to access the site, the site is accessed through a browser which is serving HTML.
There is a drop-down list that has an onChange value, which when an item is selected from the drop-down list onChange="doAction(this)" is invoked. This works fine in a desktop browser, however the iPad doesn't support the onChange. I know that an alternative is to use onBlue, however we do not have access to change the HTML.
What I was hoping we could do was to add a bookmarklet that once clicked, in principle does what the onChange event did.
The current actionlist HTML is:
<select class="actionList" onChange="doAction(this)" style="width:100%"><option class="actionHeading" selected value="nothing">Select action ..</option><option class="action" value="moreInfo"> More Info (shortcut key ' i ')</option><option class="actionHeading" disabled>Add Electronic Form ..</option><option class="action" value="xform-progressnotes-amendment-discharge"> Amendment Discharge Summary</option><option class="action" value="xform-progressnotes-clinical-review"> Clinical Review</option><option class="action" value="xform-dischargesummary"> Discharge Summary</option><option class="action" value="xform-progressnotes-family-work"> Family Work</option><option class="action" value="xform-progressnotes-medical-review"> Medical Review</option><option class="action" value="xform-medicationsummary"> Medication Summary Form</option><option class="action" value="xform-operationrecord"> Operation Sheet</option><option class="action" value="xform-progressnotes-inpatient"> Progress Notes</option><option class="action" value="xform-progressnotes-weekly-summary"> Weekly Summary</option></select></td>
The only option I would like to have in the bookmarklet is to 'select' the medical review option, i.e
<option class="action" value="xform-progressnotes-medical-review"> Medical Review</option>
the javascript for onChange="doAction(this)" is:
function doAction(selectObj)
{
var xformPrefix = 'xform-';
var chartPrefix = 'chart-';
var action = selectObj.value;
selectObj.selectedIndex = 0;
if (action == 'moreInfo')
{
moreInfo();
}
else if (action == 'referForAttn')
{
referForAttn();
}
else if(action.startsWith(chartPrefix)) {
var chartName = action.substring(chartPrefix.length);
var url;
var processedURL;
var checkExistUrl = '/udr/json/?action=chartsdescription';
checkExistUrl += '&patientId=630402';
checkExistUrl += '&chartName=' + chartName;
$.ajax({
async:false,
dataType:"json",
url:checkExistUrl,
success:function(data){
if(data.description != "")
{
var answer = confirm(data.description);
}
if(answer || data.description == "")
{
}
}
});
}
else if (action.startsWith(xformPrefix))
{
var xformName = action.substring(xformPrefix.length);
var url;
var windowWidth;
var windowHeight;
var processedURL;
if (xformName == 'progressnotes-amendment-discharge')
{
url = '/oip-forms-viewer/forms/templates?udrSessionId=BF0C3C8399163439782C67D2757477DC&formName=progressnotes-amendment-discharge&patientId=630402&episodeId=458698&transactionId=&xformAction=new§ionId=Admission';
processedURL = '%2Foip-forms-viewer%2Fforms%2Ftemplates%3FudrSessionId%3DBF0C3C8399163439782C67D2757477DC%26formName%3Dprogressnotes-amendment-discharge%26patientId%3D630402%26episodeId%3D458698%26transactionId%3D%26xformAction%3Dnew%26sectionId%3DAdmission'
windowWidth = 800;
windowHeight = 500;
}
if (xformName == 'progressnotes-clinical-review')
{
url = '/oip-forms-viewer/forms/templates?udrSessionId=BF0C3C8399163439782C67D2757477DC&formName=progressnotes-clinical-review&patientId=630402&episodeId=458698&transactionId=&xformAction=new§ionId=Admission';
processedURL = '%2Foip-forms-viewer%2Fforms%2Ftemplates%3FudrSessionId%3DBF0C3C8399163439782C67D2757477DC%26formName%3Dprogressnotes-clinical-review%26patientId%3D630402%26episodeId%3D458698%26transactionId%3D%26xformAction%3Dnew%26sectionId%3DAdmission'
windowWidth = 800;
windowHeight = 500;
}
if (xformName == 'dischargesummary')
{
url = '/oip-forms-viewer/forms/templates?udrSessionId=BF0C3C8399163439782C67D2757477DC&formName=dischargesummary&patientId=630402&episodeId=458698&transactionId=&xformAction=new§ionId=Admission';
processedURL = '%2Foip-forms-viewer%2Fforms%2Ftemplates%3FudrSessionId%3DBF0C3C8399163439782C67D2757477DC%26formName%3Ddischargesummary%26patientId%3D630402%26episodeId%3D458698%26transactionId%3D%26xformAction%3Dnew%26sectionId%3DAdmission'
windowWidth = 800;
windowHeight = 550;
}
if (xformName == 'progressnotes-family-work')
{
url = '/oip-forms-viewer/forms/templates?udrSessionId=BF0C3C8399163439782C67D2757477DC&formName=progressnotes-family-work&patientId=630402&episodeId=458698&transactionId=&xformAction=new§ionId=Admission';
processedURL = '%2Foip-forms-viewer%2Fforms%2Ftemplates%3FudrSessionId%3DBF0C3C8399163439782C67D2757477DC%26formName%3Dprogressnotes-family-work%26patientId%3D630402%26episodeId%3D458698%26transactionId%3D%26xformAction%3Dnew%26sectionId%3DAdmission'
windowWidth = 800;
windowHeight = 500;
}
if (xformName == 'progressnotes-medical-review')
{
url = '/oip-forms-viewer/forms/templates?udrSessionId=BF0C3C8399163439782C67D2757477DC&formName=progressnotes-medical-review&patientId=630402&episodeId=458698&transactionId=&xformAction=new§ionId=Admission';
processedURL = '%2Foip-forms-viewer%2Fforms%2Ftemplates%3FudrSessionId%3DBF0C3C8399163439782C67D2757477DC%26formName%3Dprogressnotes-medical-review%26patientId%3D630402%26episodeId%3D458698%26transactionId%3D%26xformAction%3Dnew%26sectionId%3DAdmission'
windowWidth = 800;
windowHeight = 500;
}
if (xformName == 'medicationsummary')
{
url = '/oip-forms-viewer/forms/templates?udrSessionId=BF0C3C8399163439782C67D2757477DC&formName=medicationsummary&patientId=630402&episodeId=458698&transactionId=&xformAction=new§ionId=Admission';
processedURL = '%2Foip-forms-viewer%2Fforms%2Ftemplates%3FudrSessionId%3DBF0C3C8399163439782C67D2757477DC%26formName%3Dmedicationsummary%26patientId%3D630402%26episodeId%3D458698%26transactionId%3D%26xformAction%3Dnew%26sectionId%3DAdmission'
windowWidth = 800;
windowHeight = 760;
}
if (xformName == 'operationrecord')
{
url = '/oip-forms-viewer/forms/templates?udrSessionId=BF0C3C8399163439782C67D2757477DC&formName=operationrecord&patientId=630402&episodeId=458698&transactionId=&xformAction=new§ionId=Admission';
processedURL = '%2Foip-forms-viewer%2Fforms%2Ftemplates%3FudrSessionId%3DBF0C3C8399163439782C67D2757477DC%26formName%3Doperationrecord%26patientId%3D630402%26episodeId%3D458698%26transactionId%3D%26xformAction%3Dnew%26sectionId%3DAdmission'
windowWidth = 800;
windowHeight = 760;
}
if (xformName == 'progressnotes-inpatient')
{
url = '/oip-forms-viewer/forms/templates?udrSessionId=BF0C3C8399163439782C67D2757477DC&formName=progressnotes-inpatient&patientId=630402&episodeId=458698&transactionId=&xformAction=new§ionId=Admission';
processedURL = '%2Foip-forms-viewer%2Fforms%2Ftemplates%3FudrSessionId%3DBF0C3C8399163439782C67D2757477DC%26formName%3Dprogressnotes-inpatient%26patientId%3D630402%26episodeId%3D458698%26transactionId%3D%26xformAction%3Dnew%26sectionId%3DAdmission'
windowWidth = 800;
windowHeight = 500;
}
if (xformName == 'progressnotes-weekly-summary')
{
url = '/oip-forms-viewer/forms/templates?udrSessionId=BF0C3C8399163439782C67D2757477DC&formName=progressnotes-weekly-summary&patientId=630402&episodeId=458698&transactionId=&xformAction=new§ionId=Admission';
processedURL = '%2Foip-forms-viewer%2Fforms%2Ftemplates%3FudrSessionId%3DBF0C3C8399163439782C67D2757477DC%26formName%3Dprogressnotes-weekly-summary%26patientId%3D630402%26episodeId%3D458698%26transactionId%3D%26xformAction%3Dnew%26sectionId%3DAdmission'
windowWidth = 800;
windowHeight = 500;
}
var newForm;
var confirmMsg = "There is another e-form opened. \n";
confirmMsg += "Press \"Cancel\" to finish editing the open e-form\n";
confirmMsg += "Press \"OK\" to discard it and open a new one.";
try {
var location = findFrame(top, 'main').win.document.location;
newForm = confirm(confirmMsg);
}
catch(e) {
newForm = true;
}
if(newForm) {
try {
findFrame(top, 'main').win.close();
}
catch(e) {}
findFrame(top, 'main').win = openCentredWindow(url, 'xformWindow', windowWidth, windowHeight);
try {
// setting the window title change on window load
$(findFrame(top, 'main').win).load(changeEformWindowTitle);
}
catch(e) {
// nothing to report
}
try {
// trying to change the window title early if the on load hasn't worked
setTimeout('changeEformWindowTitle()', 2000);
}
catch(e) {
// nothing to report
}
try {
// doing it a second time in case the first attempt was too early.
setTimeout('changeEformWindowTitle()', 8000);
}
catch(e) {
// nothing to report
}
try {
// doing it a third time 40 seconds later in case it there was a pre-fill.
setTimeout('changeEformWindowTitle()', 40000);
}
catch(e) {
// nothing to report
}
}
else {
findFrame(top, 'main').win.focus();
}
}
}
Any help you could provide would be very much appreciated!
Thanks.
Your best bet is to place a proxy server between the ipad and the actual product.
This proxy can then modify the html generated by the proprietary system.
You can look into nginx as a newbie friendly solution for proxying.
Cheers,
T.
PS : I dont believe bookmarklets work on iPads. Even if they did, it would be a terrible UI.
I'm trying to combine all scripts into one.. I have two folders, the main folder 'scripts' and the other 'scripts/other'.
When I try:
BundleTable.Bundles.Add(new ScriptBundle("~/scripts/all").Include("~/Scripts/*.js", "~/Scripts/other/*.js"));
scripts from 'scripts/other' are not included.
but when I invert the order:
BundleTable.Bundles.Add(new ScriptBundle("~/scripts/all").Include("~/Scripts/other/*.js", "~/Scripts/*.js"));
it works!!
Someone can tell me why?
Can you try calling the IncludeDirectory methods directly and seeing if you see the same issue?
ScriptBundle("~/scripts/all").IncludeDirectory("~/Scripts", "*.js").IncludeDirectory("~/Scripts/other", "*.js"));
If this works, then it's possible we have a bug here.
I don't know what is happening, but this is the code inside the System.Web.Optimization.Bundle:
// System.Web.Optimization.Bundle
public Bundle Include(params string[] virtualPaths)
{
for (int i = 0; i < virtualPaths.Length; i++)
{
string text = virtualPaths[i];
Exception ex = Bundle.ValidateVirtualPath(text, "virtualPaths");
if (ex != null)
{
throw ex;
}
if (text.Contains('*'))
{
int num = text.LastIndexOf('/');
string text2 = text.Substring(0, num);
if (text2.Contains('*'))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, OptimizationResources.InvalidPattern, new object[]
{
text
}), "virtualPaths");
}
string text3 = "";
if (num < text.Length - 1)
{
text3 = text.Substring(num + 1);
}
PatternType patternType = PatternHelper.GetPatternType(text3);
ex = PatternHelper.ValidatePattern(patternType, text3, "virtualPaths");
if (ex != null)
{
throw ex;
}
this.IncludeDirectory(text2, text3);
}
else
{
this.IncludeFile(text);
}
}
return this;
}
I would like to allow the user of my XULRunner based app to be able to do copy/paste via a context menu.
Keyboard shortcuts Ctrl-C and Ctrl-V are already working fine
Here it is without flash. The getInputSelection function is from here: Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?.
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="mywin" title="my app"
width="800" height="600" persist="screenX screenY width height sizemode"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<popupset>
<menupopup id="clipmenu">
<menuitem label="Copy" oncommand="copy()"/>
<menuitem label="Paste" oncommand="paste();"/>
</menupopup>
</popupset>
<browser
type="content-primary"
src="http://127.0.0.1/"
flex="1"
disablehistory="true"
id="browserId"
context="clipmenu"
/>
<script>
<![CDATA[
function copy()
{
var tabBrowser = document.getElementById("browserId");
var selectedTagName = tabBrowser.contentWindow.document.activeElement.tagName;
var windowObj;
if(selectedTagName == "IFRAME")
{
windowObj = tabBrowser.contentWindow.frames[tabBrowser.contentWindow.document.activeElement.name];
}
else
{
windowObj = document.getElementById("browserId").contentWindow;
}
var selectedText = windowObj.getSelection();
if(!selectedText || selectedText == "")
{
var focused = windowObj.document.activeElement;
if(focused && focused.value)
{
selectedText = getSelectionFromInput(focused);
}
}
//alert(selectedText + "---");
const clipHelper = Components.classes["#mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
clipHelper.copyString(selectedText);
}
function getSelectionFromInput(focused)
{
var focusedValue = focused.value;
var sel = getInputSelection(focused);
var selectedText = "";
if(focusedValue.length == (sel.end))
{
selectedText = focusedValue.substring(sel.start);
}
else
{
selectedText = focusedValue.substring(sel.start, (sel.end));
}
return selectedText;
}
function paste()
{
var clip = Components.classes["#mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
var trans = Components.classes["#mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
trans.addDataFlavor("text/unicode");
clip.getData(trans, clip.kGlobalClipboard);
var str = new Object();
var len = new Object();
trans.getTransferData("text/unicode",str,len);
str = str.value.QueryInterface(Components.interfaces.nsISupportsString);
str = str.data.substring(0, len.value / 2);
var focused = document.commandDispatcher.focusedElement;
var focusedValue = focused.value;
var sel = getInputSelection(focused);
focused.value = focusedValue.substring(0,sel.start) + str + focusedValue.substring(sel.end);
}
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
]]>
</script>
</window>
Updated to support iframes.
Create menu using the code below.
<popupset>
<menupopup id="clipmenu">
<menuitem label="Copy" oncommand="copy();"/>
<menuseparator/>
<menuitem label="paste" oncommand="paste();"/>
</menupopup>
</popupset>
<browser type="content" src="chrome://myapp/content/theme1/index.html" flex="1" context="clipmenu"/>
Connect it to whatever you want, here am making it the context menu of the browser element by giving the id of menu in the context attribute of the browser element.
Then for each menu you can give the command to execute in oncommand event. We have given the function copy and paste.
Then write the code to copy text from whatever element you want or if you want to copy the selected data only.
See the below link for copying command.
http://www.deluxeblogtips.com/2010/06/javascript-copy-to-clipboard.html
One more example for "Copy" context menu in XULRunner under SWT Browser (code was implemented for Eclipse v3.5.1, XULRunner v1.8.1.3):
Browser browser = new Browser(parent, style | SWT.MOZILLA);
Menu menu = new Menu(browser);
MenuItem item = new MenuItem(menu, SWT.NONE);
item.setText("Copy");
item.addSelectionListener(new SelectionListener() {
#Override
public void widgetSelected(SelectionEvent e) {
nsIWebBrowser webBrowser = (nsIWebBrowser) browser.getWebBrowser();
nsIInterfaceRequestor req = (nsIInterfaceRequestor) webBrowser.queryInterface(nsIInterfaceRequestor.NS_IINTERFACEREQUESTOR_IID);
nsIDocShell docShell = (nsIDocShell) req.getInterface(nsIDocShell.NS_IDOCSHELL_IID);
nsIClipboardCommands cmds = (nsIClipboardCommands) docShell.queryInterface(nsIClipboardCommands.NS_ICLIPBOARDCOMMANDS_IID);
cmds.copySelection();
}
#Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
browser.setMenu(menu);