firefox add-on innerHTML not allowed, DOM help needed - javascript

I'm writing my first firefox add-on.
It was completed, but mozilla rejected it with this answer:
1) Your add-on creates DOM nodes from HTML strings containing potentially unsanitized data, by assigning to innerHTML or through similar means. Aside from being inefficient, this is a major security risk. For more information, see https://developer.mozilla.org/en/XUL_School/DOM_Building_and_HTML_Insertion. Here are some examples where you do this: (cut...)
I wrote:
var myDiv = content.document.getElementById("myContent");
myDiv.innerHTML = "some html code";
now I'm not a JS programmer and I don't understand how to go on.
I tested some code like this:
var NewNode = content.document.createElement("span");
NewNode.appendChild(content.document.createTextNode("Hello World!"));
//content.document.body.appendChild(NewNode);//ok, works
content.document.getElementById("myContent").appendChild(NewNode);//doesn't work
but it doesn't work until I append it to .body
Samples working on other pages seems not working here. Moreover I don't understand if it fixes the problem that mozilla indicated.
Could you please help me with the code that should replace the two lines I wrote?
If you need the full code, here it is: http://www.maipiusenza.com/LDV/down/ldvgenerator.xpi
Thanks!
Nadia

Just did a quick js fiddle, I was wondering why you have used content.document so I amended it to document and it worked.
http://jsfiddle.net/eDW82/
var NewNode = document.createElement("span");
NewNode.appendChild(document.createTextNode("Hello World"));
document.getElementById("myContent").appendChild(NewNode);
I had a similar problem with unsanitized HTML and as I used it extensively I opted to use jQuery which will pass mozillas rules. It makes life a lot easier to be able to create your nodes that way.
$("<div>", {id:"example"}).text("Hello World")
It just reads so much nicer.

OK then, I did some digging and I think I managed to find your problem:
Whenever you want to inject any kind of html to your extension, The browser considers it as a security hole, that's why you have this problem. you have 2 different solution;
first: you can create an iframe and use it to show your html (in javascript whenever we want to show a file we have 2 option, first pass a file path on the server, or use data: to show your data directly):
var htmlStr = "<span>Hello World!</span>";
var frm = content.document.createElement("iframe");
content.document.getElementById("myContent").appendChild(frm);
frm.src = "data:text/html;charset=utf-8," + encodeURIComponent(htmlStr);
second: this solution would help you out, if you don't want to use an iframe to show your html.
var htmlStr = "<span>Hello World!</span>";
var frm = document.createElement("iframe");
frm.style.display="none";
document.body.appendChild(frm);
var win = frm.contentWindow;
var frmrange = win.document.createRange();
// make the parent of the first div in the document becomes the context node
frmrange.selectNode(win.document.firstChild);
var frg = frmrange.createContextualFragment(htmlStr);
content.document.getElementById("myContent").appendChild(frg);
Old Guess: the problem in your code is different document objects, try this:
var NewNode = content.document.createElement("span");
NewNode.appendChild(content.document.createTextNode("Hello World!"));
content.document.getElementById("myContent").appendChild(NewNode);
this was my first clue to point out.

Related

Run script after appending it to the HTML

I have a string with HTML:
var str = '<div><p>Examplee</p></div><script>alert("testing!")</script>';
and then I append it to the HTML:
document.body.innerHTML += str;
and the content is appended but the script does not execute, is there a way to force it?
First, a caveat: Naturally, only do this with scripts you trust. :-)
There are a couple of ways. Basically, you need to:
Get the text of the script, and
Run it
Getting the text
One option is just to go ahead and add it, then find it and grab its text:
document.body.innerHTML += str;
var scripts = document.querySelectorAll("script");
var text = scripts[scripts.length - 1].textContent;
On obsolete browsers, you may need to feature-detect textContent vs. innerText.
You might want to give it an identifying characteristic (id, class, etc.) so you don't have to find it by position like that.
Alternately, you could do what the PrototypeJS lib does and try go get it from the string with regex. You can find their source code for doing that here (look for extractScripts).
Running it
Once you have the text of the script, you have several options:
Use indirect eval (aka "global eval") on it: (0, eval)(text). This is not the same as eval(text); it runs the code in global scope, not local scope.
Create a new script element, set its text to the text, and add it
var newScript = document.createElement("script");
newScript.textContent = text;
document.body.appendChild(newScript);
If doing that, might make sense to remove the original, though it doesn't really matter.
Example that grabs the text of the script element after adding it and uses indirect eval:
var str = '<div><p>Examplee</p></div><script>alert("testing!")<\/script>';
document.body.innerHTML += str;
var scripts = document.querySelectorAll("script");
(0, eval)(scripts[scripts.length - 1].textContent);
Presumably you don't really use += on document.body.innerHTML, which builds an HTML string for the whole page, appends to it, tears the whole page down, and then parses the new HTML to build a new one. I assume that was just an example in your question.
jQuery provides the $.getScript(url [,success]) function. You can then load and execute your code from a separate jquery file which helps to manage and control the flow of execution.
basically put your alert("testing!") script inside a separate file, for instance alert.js in the same directory.
Then you can run the script when adding your employee to the HTML.
var str = '<div><p>Examplee</p></div>';
var url = 'alert.js';
document.body.innerHTML += str;
$.getScript(url);
I know this may seem like more work, but it is better practice to keep your javascript out of your HTML. You can also use a callback to gather user data after the alert or notify another process that the user has been alerted.
$.getScript(url, function(){
//do something after the alert is executed.
});
For instance maybe it would be a better design to add the employee after the alert is executed.
var str = '<div><p>Examplee</p></div>';
var url = 'alert.js';
$.getScript(url, function(){
document.body.innerHTML += str;
});
Edit: I know jQuery is not tagged, but I am also no petitioning to be the accepted answer to this question. I am only offering another alternative for someone who may run into the same issue and may be using jQuery. If that is the case $.getScript is a very useful tool designed for this exact problem.
You should change the HTML after it was loaded.
Try this:
document.addEventListener("DOMContentLoaded", function(event) {
document.body.innerHTML += str;
});

Print html to a surface to be copied

I stored an table's html as a text, using this code.
var Data = document.getElementsByClassName("result")[0].innerHTML;
I am able to observe the selected part using console.log, however, I wish to extract this data to be copied and used outside.
So I tried alert(Data), but it does not offer a good surface to copy the data (it does work though, however I cannot use right click on the pop-up window)
I also tried to programmatically copy the data to the clipboard, but it seems, it only works on selected text data.
Is there a better way to extract such data to be used outside ?
Note: I am using a firefox bookmark to execute javascript. But I expect the code to work also in the other browsers.
Edit: I tried the method suggested in the comments, however in firefox, I got an error.
document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler.
So rather than copying with that command, printing to a surface seems a better choice, if possible. The linked question does not solve my issue.
Edit2: window.prompt did a much better job, however it rocked my world by pressing the text to a single line. I still should be able to parse it programmatically, but if there is a better answer, I wish to learn it.
Below is my solution to keep multiple lines.
It creates one temp 'textarea', then remove it after select()->copy.
function triggercopy() {
var target_obj = document.getElementById('test1');
var copy_text = target_obj.innerHTML; //replace with your actual data.
var hidden_obj = document.createElement("textarea");
hidden_obj.value = copy_text;
document.body.insertBefore(hidden_obj,target_obj);
console.log('prepare:' + copy_text);
hidden_obj.select();
document.execCommand("copy");
document.body.removeChild(hidden_obj);
console.log('already copied:' + copy_text);
}
Text3as
dfsadf
<a id="test1" onclick="triggercopy();">Text3as
dfsadf</a>
I found two methods best suit my interests.
First, window.prompt:
var Data = document.getElementsByClassName("result")[0].innerHTML;
function copyToClipboard(text) {
window.prompt("Copy data.", text);
}
copyToClipboard(Data)
This is a good method, taken from a suggested answer. This puts the data into a single-line text field. And in an interesting manner, when written without a function, executes document.write(Data) when clicked OK, this does not happen when written in a function as above.
Second, document.write:
var target = document.getElementsByClassName("resultTable striped")[0].outerHTML;
document.open('text/plain');
document.write(target);
I first tried to open a new tab with the desired content, however encountered with the issue of pop-up blockers and non-plain text html data (formatted html instead of the desired table html data). This solves both issues.

JavaScript: Change objectHTMLScriptElement

I am currently working within a CMS, cleaning up 12 websites.
Currently there are 12 identical JS files each residing within their respective site. Since they are all the same, my first initiative is to point every site to a single JS file that lives on the server.
Because I'm working within a CMS, I would have to open up 200 templates to accomplish this feat manually, so I'd, of course, rather do this dynamically.
Here is what I have done, so far:
var scripts = document.getElementsByTagName ("script");
console.log(scripts[15]);
My console.log statement returns what I'd like to replace, which is this:
<script src="/Assets/AmericanTower.com.br/uploads/content/js/main.js">
When I use alert(); rather than console.log(); I get this:
[object HTMLScriptElement]
I don't really understand why alert and console.log are showing me 2 different results.
So, I gather that I need to find a way to convert this HTMLElement to a string and then replace the string(or part of it) with the path to my new JS file.
Can anyone please shed some light?
Thank you in advance!
Robin
===============================
Thank you, L.C. Echo Chan, for your contribution. Here's how I used your suggestion and it worked like a charm!
var scripts = document.getElementsByTagName("script");
var jsPath=scripts[15].outerHTML;
var changedURL=jsPath.replace(jsPath,"RegionalGlobalAssets");
alert(changedURL);
Using outerHTML property can return the entire element
var scripts = document.getElementsByTagName("script");
alert(scripts[15].outerHTML);
Try to set you code as that
var scripts = document.getElementsByTagName("script");
console.log(scripts[15]);

replace with regex then undo

I have a rather unique problem where I'm trying to run some jquery logic to replace text temporarily on a page. Then run some logic (I take a screenshot for a tool I'm using). So far this works great, the problem is that due to legacy code I need to revert the changes the replace call did on the page.
Any ideas on the best way to do this?
For the curious, I currently have:
$('body').html($('body').html().replace(/[a-zA-Z0-9\\*]*#.*\\.com/g,'[replaced for screenshot]'))
Thanks!
I'd question your motives and reasoning, but I'll provided an answer nonetheless:
var backup_body_html = $('body').html();
$('body').html(backup_body_html.replace(/[a-zA-Z0-9\\*]*#.*\\.com/g,'[replaced for screenshot]'));
Afterwards:
$('body').html(backup_body_html);
(Unless you need to keep hold of event handlers etc, in which case cloning is needed)
Cloning method:
var body_children = $("body").clone(true,true).children();
//other stuff (i.e. replacements)
//then:
$("body").html("");
$("body").append(body_children);
Not completely serious but I have to...
location.reload();
Before
var bodyHTML = document.body.innerHTML;
$('body').html(bodyHTML.replace(/[a-zA-Z0-9\\*]*#.*\\.com/g,'[replaced for screenshot]'));
After
$('body').html(bodyHTML)

How to increase speed of getElementById() function on IE or give other solutions?

I have a project using Javascript parse json string and put data into div content.
In this case, all of itemname variables is the same div's id.
If variable i about 900, I run this code in Firefox 3 for <10ms, but it run on IE 7 for >9s, IE process this code slower 100 times than Firefox
I don't know what happen with IE ?
If I remove the line document.getElementById(itemname), speed of them seems the same.
The main problem arcording to me is document.getElementById() function?
Could you show me how to solve this prolem to increase this code on IE ?
Thank in advance.
var i = obj.items.length-2;
hnxmessageid = obj.items[i+1].v;
do{
itemname = obj.items[i].n;
itemvalue = obj.items[i].v;
document.getElementByid(itemname);
i--;
}while(i>=0);
Are you really noticing any latency?
gEBI is natively very very fast, I don't think you can avoid it anyway for what you're doing. Could you provide a low-down of what you're doing precisely? It looks like you're using a loop, but can you post exactly what you're doing inside of the loop, what your common goal of the script is?
document.getElementByid(itemname) is the fastest way to get a single element from the DOM in any real application you will sould not see any problems with using it, if you do see a problem you need to rethink you code a little it possible to acomplish any task with just a handfull of calls for this method. You can present you full problem if you like so I could show you an example
At least cache the reference to document:
var doc = document;
for(;;) {
doc.getElementById(..);
}

Categories

Resources