Appending XUL element (s) into DOM from a string of markup - firefox

I am writing a Firefox extension using JavaScript and XUL. Part of my code needs to be able to take some XUL markup and dynamically append it inside an existing container element. So basically I need to appendChild() but with a text string instead of a Node object. To do this, I tried the method listed in this question. Unfortunately this does not seem to work. It appears that div.childNodes returns an empty nodeList, which I can't even append to the container. The error is
Error: Could not convert JavaScript argument arg 0 [nsIDOMXULElement.appendChild]
I'm not quite sure what I am doing wrong. Is there a way to make this work, or some alternate method to dynamically set the container's markup?
Note: The container element is of type richlistbox.
function updateContainerData(containerName){
try{
var resultsArray = DB.queryAsync("SELECT nodeData FROM waffleapps_privateurl");
container = document.getElementById(containerName);
for (var i = 0; i < resultsArray.length; i++) {
/*
// This works - appending an actual Node ( duplicate from a template)
template = document.getElementById("list-item-template");
dupNode = template.cloneNode(true);
dupNode.setAttribute("hidden", false);
container.appendChild(dupNode);
*/
// This doesn't work
div = document.createElement("div");
//var s = '<li>text</li>';
var s = "<richlistitem id ='list-item-template'><hbox><checkbox label='' checked='true'/> <description>DESCRIPTION</description><textbox>test</textbox><textbox></textbox></hbox></richlistitem>";
div.innerHTML = s;
var elements = div.childNodes;
container.appendChild(elements); // error
}
}
catch(err){
alert( "Error: " + err.message);
}
}
I have gotten a bit further by using the following code. Now I am able to insert HTML elements in the container, but it appears that XUL elements are not parsed properly - the checkbox and textbox do not appear. I'm not sure how I would change this so it parses the HTML and XUL markup correctly.
var s = "<richlistitem id ='list-item-template'><hbox><checkbox label='' checked='true'/> <description>DESCRIPTION</description><textbox>test</textbox><textbox></textbox></hbox></richlistitem>";
var dp = new DOMParser();
container.appendChild(dp.parseFromString(s, "text/xml").documentElement);

You need to do an appendChild for each element in the "elements" nodeList (assuming there's more than one).
Also note: a list element should have a parent ol or ul element.

I finally figured out how to properly parse and append a XUL markup string. I was able to use the parseFromString method from a new DOMParser(). I had to make sure that the element's markup specified the namespace (xmlns) so the parser knew it was XUL markup.
The code below shows a full example.
test.js:
test = function(){
alert("testing");
container = document.getElementById("testing");
var dp = new DOMParser();
// must specify namespace
var s = "<textbox xmlns='http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul' value='test' size='20'></textbox>";
element = dp.parseFromString(s, "text/xml").documentElement;
container.appendChild(element);
document.getElementById("testing");
}
test.xul:
<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="chrome://global/skin/" ?>
<?xml-stylesheet type="text/css"
href="chrome://testextensionname/skin/test.css" ?>
<!DOCTYPE window SYSTEM
"chrome://testextensionname/locale/test.dtd">
<window xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
id="testWindow"
orient="vertical" title="TEST" statictitle="TEST"
width="50" height="50;" screenX="10" screenY="10"
>
<script type="application/x-javascript" src="chrome://testextensionname/content/test.js" />
<hbox id="testing">
<button label="Go" oncommand="test()"/>
<textbox value='test' size='20'></textbox>
</hbox>
</window>

Related

How do I inject a custom component from js in nativescript?

Suppose I create a small component that takes an input and sets a label to show it.
app/components/testComponent/testComponent.xml:
<Label id="someLabel" loaded="onLoad"/>
app/components/testComponent/testComponent.js:
exports.onLoad = args => {
const obj = args.object;
const label = obj.getViewById('someLabel');
label.text = obj.someString || 'no string given';
};
Now I can use this component in any of my pages
<Page xmlns="http://schemas.nativescript.org/tns.xsd"
xmlns:testComponent="components/testComponent">
<StackLayout>
<testComponent:testComponent someString="hello {N}"/>
</StackLayout>
</Page>
This seems to be the official way to do it and it works. But is there a way to inject this component in the page using javascript only?
Yes, the Declarative UI (i.e. xml) is actually a building system that parses the xml and generates the JS so you don't have to.
So if you wanted to manually do this you would leave your component code alone and you would change your main screen code to be like this:
<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="onLoad">
<StackLayout id='sl'>
</StackLayout>
</Page>
The first thing you will notice is we gave the Page a loaded event, you have to have somewhere to actually run your code to attach your component to the visual tree. The second thing we did was add to StackLayout an id; this technically isn't actually needed -- you can navigate the NS tree and find the proper StackLayout; but for simplicity adding a ID makes it a lot easier.
So the JS code in your page would be:
var builder = require('ui/builder');
var fs = require('file-system');
exports.onLoad = function(args) {
// Get our current Page that is being loaded
var page = args.object;
// Find our StackLayout
var stackLayout = page.getViewById('sl');
// Load our JS for the component
var path = fs.knownFolders.currentApp().path;
var componentJS = require(path + '/components/testComponent/testComponent.js');
// Actually have the builder build the Component using the XML & JS.
var component = builder.load(path + '/components/testComponent/testComponent.xml', componentJS);
// And add our component to the visual tree
stackLayout.addChild(component);
};
I believe that because you are adding the child in the loaded event that your page loaded event in the child component will be ran, but don't hold me to that one. If it isn't then you can manually run it a the same time you are adding it...
where filepath is a script - or even a class the callback function can create an instance of.
This is as if its loaded at page load and shows in most developer tool consoles.
var uuid='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
var url = filepath + "?" + uuid;//prevent caching - does not work with ajax setup
try {
$.getScript(url, "callbackfunctionname('" + filepath + "')");//getScript callback seems broken so use own
}
catch (e) {
//error handle
}

Rich Text Editor (WYSIWYG) in CRM 2013

Sometimes it is useful to have the HTML editor in CRM interface. It is possible to implement the editor directly to CRM 2013. As editor we will use ckeditor which allows to use it without installation on the server.
Identify the field where you would like to use the rich text editor.
Create html-webresource which will define ckeditor. Go to Settings-Customizations-Customize the System-Web Resources.
In html editor of web resource, select the Source tab and insert the following code:
<html>
<head>
<title></title>
<script src="//cdn.ckeditor.com/4.4.7/standard/ckeditor.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getTextFieldName()
{
var vals = new Array();
if (location.search != "")
{
vals = location.search.substr(1).split("&");
for (var i in vals)
{
vals[i] = vals[i].replace(/\+/g, " ").split("=");
}
//look for the parameter named 'data'
for (var i in vals)
{
if (vals[i][0].toLowerCase() == "data")
{
var datavalue = vals[i][2];
var vals2 = new Array();
var textFieldName = "";
vals2 = decodeURIComponent(datavalue).split("&");
for (var i in vals2)
{
var queryParam = vals2[i].replace(/\+/g, " ").split("=");
if (queryParam[0] != null && queryParam[0].toLowerCase() == "datafieldname")
{
textFieldName = queryParam[1];
}
}
if (textFieldName == "")
{
alert('No "dataFieldName" parameter has been passed to Rich Text Box Editor.');
return null;
}
else
{
return textFieldName;
}
}
else
{
alert('No data parameter has been passed to Rich Text Box Editor.');
}
}
}
else
{
alert('No data parameter has been passed to Rich Text Box Editor.');
}
return null;
}
CKEDITOR.timestamp = null;
​// Maximize the editor window, i.e. it will be stretched to target field
CKEDITOR.on('instanceReady',
function( evt )
{
var editor = evt.editor;
editor.execCommand('maximize');
});
var Xrm;
$(document).ready(function ()
{
​ // Get the target field name from query string
var fieldName = getTextFieldName();
var Xrm = parent.Xrm;
var data = Xrm.Page.getAttribute(fieldName).getValue();
document.getElementById('editor1').value = data;
/*
// Uncomment only if you would like to update original field on lost focus instead of property change in editor
//Update textbox on lost focus
CKEDITOR.instances.editor1.on('blur', function ()
{
var value = CKEDITOR.instances.editor1.getData();
Xrm.Page.getAttribute(fieldName).setValue(value);
});
*/
// Update textbox on change in editor
CKEDITOR.instances.editor1.on('change', function ()
{
var value = CKEDITOR.instances.editor1.getData();
Xrm.Page.getAttribute(fieldName).setValue(value);
});
// Following settings define that the editor allows whole HTML content without removing tags like head, style etc.
CKEDITOR.config.allowedContent = true;
CKEDITOR.config.fullPage = true;
});
</script>
<meta>
</head>
<body style="word-wrap: break-word;">
<textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"></textarea>
</body>
</html>
Note:
As you can see, there are a few important sections
a) The following code loads the ckeditor and jquery from web so that they don't have to be installed on server.
<script src="//cdn.ckeditor.com/4.4.7/standard/ckeditor.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
b) Function getTextFieldName() which gets the name of target field where should be rich text editor placed. This information is obtained from query string. This will allow to use this web resource on multiple forms.
c) Initialization of ckeditor itself - setting the target field and properties of ckeditor. Also binding the editor with predefined textarea on the page.
Open the form designer on the form where you would like to use ​WYSIWYG editor. Create a text field with sufficient length (e.g. 100 000 chars) which will hold the html source code.
Insert the iframe on the form. As a webresource use the resource created in previous steps. Also define Custom Parameter(data) where you should define the name of the text field defined in step 4. In our situation we created new_bodyhtml text field so the parameter holds this value. This value is returned by the getTextFieldName() of the web resource.
Do not forget to save and publish all changes in CRM customization otherwise added webresources and updated form are not available.
That's all, here is example how it looks like:
Yes, you can use CKEditor, but when I implemented the CKEditor on a form, it turns out it is quite limited in the functionality in provides. Also, the HTML it generates leaves much to be desired. So, I tried a similar idea to Pavel's but using a backing field to store the actual HTML using TinyMCE. You can find the code here:
Javascript
HTML
Documentation
I have package my solution as a managed and unmanaged CRM solution that can be imported and utilised on any form. Moreover, it works on both CRM 2013 and CRM 2015

CKEDITOR - how to add permanent onclick event?

I am looking for a way to make the CKEDITOR wysiwyg content interactive. This means for example adding some onclick events to the specific elements. I can do something like this:
CKEDITOR.instances['editor1'].document.getById('someid').setAttribute('onclick','alert("blabla")');
After processing this action it works nice. But consequently if I change the mode to source-mode and then return to wysiwyg-mode, the javascript won't run. The onclick action is still visible in the source-mode, but is not rendered inside the textarea element.
However, it is interesting, that this works fine everytime:
CKEDITOR.instances['editor1'].document.getById('id1').setAttribute('style','cursor: pointer;');
And it is also not rendered inside the textarea element! How is it possible? What is the best way to work with onclick and onmouse events of CKEDITOR content elements?
I tried manually write this by the source-mode:
<html>
<head>
<title></title>
</head>
<body>
<p>
This is some <strong id="id1" onclick="alert('blabla');" style="cursor: pointer;">sample text</strong>. You are using CKEditor.</p>
</body>
</html>
And the Javascript (onclick action) does not work. Any ideas?
Thanks a lot!
My final solution:
editor.on('contentDom', function() {
var elements = editor.document.getElementsByTag('span');
for (var i = 0, c = elements.count(); i < c; i++) {
var e = new CKEDITOR.dom.element(elements.$.item(i));
if (hasSemanticAttribute(e)) {
// leve tlacitko mysi - obsluha
e.on('click', function() {
if (this.getAttribute('class') === marked) {
if (editor.document.$.getElementsByClassName(marked_unique).length > 0) {
this.removeAttribute('class');
} else {
this.setAttribute('class', marked_unique);
}
} else if (this.getAttribute('class') === marked_unique) {
this.removeAttribute('class');
} else {
this.setAttribute('class', marked);
}
});
}
}
});
Filtering (only CKEditor >=4.1)
This attribute is removed because CKEditor does not allow it. This filtering system is called Advanced Content Filter and you can read about it here:
http://ckeditor.com/blog/Upgrading-to-CKEditor-4.1
http://ckeditor.com/blog/CKEditor-4.1-Released
Advanced Content Filter guide
In short - you need to configure editor to allow onclick attributes on some elements. For example:
CKEDITOR.replace( 'editor1', {
extraAllowedContent: 'strong[onclick]'
} );
Read more here: config.extraAllowedContent.
on* attributes inside CKEditor
CKEditor encodes on* attributes when loading content so they are not breaking editing features. For example, onmouseout becomes data-cke-pa-onmouseout inside editor and then, when getting data from editor, this attributes is decoded.
There's no configuration option for this, because it wouldn't make sense.
Note: As you're setting attribute for element inside editor's editable element, you should set it to the protected format:
element.setAttribute( 'data-cke-pa-onclick', 'alert("blabla")' );
Clickable elements in CKEditor
If you want to observe click events in editor, then this is the correct solution:
editor.on( 'contentDom', function() {
var element = editor.document.getById( 'foo' );
editor.editable().attachListener( element, 'click', function( evt ) {
// ...
// Get the event target (needed for events delegation).
evt.data.getTarget();
} );
} );
Check the documentation for editor#contentDom event which is very important in such cases.

Virtual area around vml element

this is my first post, so my deepest excuses if something went wrong :)
I have a little html-control to write and biggest problem is ie6-8 support. There are no alternatives to skip ie6-8 support at all :( So after searching a while, I did found Raphael and it allows me to create custom shapes defined in SVG file. I need to attach 'mouseover' event and select element on hover. Event working great but I did find BIG problems in VML hover behavior.
Code was simplified to RAW html with VML shape.
<html xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<style>v\: * { behavior:url(#default#VML); antialias: false; }</style>
</head>
<body>
<div id="message">hovered: nope</div>
<v:oval id="oval" style="width:100px; height:75px" fillcolor="#bbb"></v:oval>
<script>
var messageElm = document.getElementById('message');
var ovalElm = document.getElementById('oval');
ovalElm.attachEvent('onmouseover', function () { messageElm.innerText = 'hovered: yep'; });
ovalElm.attachEvent('onmouseout', function () { messageElm.innerText = 'hovered: nope'; });
</script>
</body>
</html>
If you try to move mouse over oval element you can noticed that rendered shape is not same as hover shape. I mean, hover triggers 2-3px from rendered shape (not from each side).
So question is: how to disable that virtual area (if it is possible at all)?
i had the same issue and i tried usemap;
first i create a map on a transparent png8 which covered the vml
this.dom.insertAdjacentHTML("AfterBegin",'<map name="'+_id+'"></map><img id="'+_id+'" src="'+transparent.png+
'" style="position:absolute;width:'+dom.clientWidth+';height:'+dom.clientHeight+'" />');
var map = this.dom.getElementsByTagName('map')[0];
this.dom.appendChild(map);
this.map = map;
then get the shape attach to an area; map it;
i made poly demo only;
function _getMap(shape){
this._map = this._map || {};
if(this._map[shape.id]){
}else if(shape.nodeName == 'shape'){
var arrDots = shape.childNodes[0].v.match(/(\d+),(\d+)/g)
this._map[shape.id] = _polyMap(arrDots);
}
return this.map[shape.id]
}
function _polyMap(arrDots){
var map = this.map;
var area = document.createElement('area');
area.setAttribute('shape',"poly");
area.setAttribute('coords',arrDots.join(','));
area.setAttribute('href','##');
area.setAttribute('alt','##');
map.appendChild(area);
}
then you can bind event on it;
function _onIE(shape, evtname, fn){
this._getMap(shape).attachEvent('on'+evtname, fn);
}

Firefox Extensions HTML Injection on the fly?

Hi I followed the instructions to create an extension.
My issue is that I can inject text on the fly but not HTML. Firefox block the character "<"
Here is my code in my XUL file.
<?xml version="1.0"?>
<overlay id="sample"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script src="jquery.js" />
<script>
var myExtension = {
init: function() {
// The event can be DOMContentLoaded, pageshow, pagehide, load or unload.
if(gBrowser) gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad, false);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered the event
var win = doc.defaultView; // win is the window for the doc
if (win != win.top) return; //only top window.
$("body",doc).html('WORK');
$("body",doc).html('<div>NOT WORKING</div>');
}
}
window.addEventListener("load", function() { myExtension.init(); }, false);
</script>
</overlay>
Thank you very much for your help
This is a XUL file, it has to use XML syntax. In particular, XML tags inside <script> elements will be interpreted as such - and you definitely don't want it. To prevent it you can wrap your script into a CDATA section:
<script>
<![CDATA[
doSomething("<foo>bar</foo>");
]]>
</script>
This makes sure that the tag contents are really interpreted as text.

Resources