I have a javascript code that replace some words writen in text area. Eg. If I write word "dog" it will change it to word "cat".
<html>
<head>
<script>
function changeText(){
dt=document.getElementsByTagName("textarea")[0];
dt.value=dt.value.replace(/dog/g,"cat");
dt.value=dt.value.replace(/blue/g,"red");
dt.value=dt.value.replace(/good/g,"bad");
}
</script>
</head>
<body>
<textarea rows="10" cols="65"></textarea> <br>
<input type="button" value="change" onclick="changeText()">
</body>
</html>
I have two problems with this script and I don't know how to fix it.
How can I call external file with words for replacement? I will have 200+ words and it will better that I have them in separate file.
How to implement some simple RTE (eg. Nicedit) and still have working script? I try it and script doesn't work...
Thanks in advance for help! :)
Due to security reasons, your possibilites are limited. The best way to do it is to load txt/json/xml file from your server using AJAX technology. Keep in mind that it's an asynchronous method. Without JQuery (most popular JS library), with pure Javascript, you can achieve it with the code below:
var fileContent = '';
var client = new XMLHttpRequest(); // we create a request
client.open('GET', '/foo.txt'); // foo.txt is the name of the file
client.onreadystatechange = function() {
fileContent = client.responseText;
alert("Hooray! My file was loaded, this is its content: " + fileContent );
}
client.send(); // and we send a request
Every rich text editor has its own JS library and a way to get editor's content, so it really depends. For nicedit it's like this (assuming your textarea has an ID):
var nicInstance = nicEditors.findEditor('idOfYourTextarea');
var notes = nicInstance.getContent(); // voila - your content
Related
I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});
I just started working on my school assignment with some regular expressions in Javascript. I can't seem to figure out how to actually read data from a text file into variable using jQuery method .get(). When I try my code out nothing happens. It seems like it never enters .get() section. Here is my code:
JS file:
document.getElementById('file').onchange = function(){
var file = "New Text Document.txt"; //this will later be the selected file
$.get(file,function(data){
var myVar = data;
$("#123").html(myVar);
});
};
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>animacija</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<script type="text/javascript" src="func.js"></script>
<div id="123"></div>
</body>
</html>
The code snippet seems to be ok, but it will not work locally since $.get is for ajax requests and requires full available server path.
I rather recommend you the use of FileReader API.
HTML
<title>animacija</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<input type="file" name="file" id="file">
<div id="123"></div>
</body>
JavaScript
document.getElementById('file').onchange = function() {
var file = this.files[0];
var FR = new FileReader();
FR.readAsText(file);
FR.onload = function(data) {
var myVar = data.target.result;
$("#123").html(myVar);
}
};
JSFiddle
Hope it works for you!
Most browsers will not allow file: resources to read other local files. This is to prevent attacks where a downloaded HTML document could start reading (and transmitting) the contents of your hard drive (or at least your Downloads folder) as soon as you open it.
The other thing you need to know here is that $.get is used for getting resources from an HTTP server, while file inputs are used to allow a user to select a file from their local drive. I realize in your case it's a little confusing, because your web page is on your local hard drive, but imagine if your HTML and scripts were being hosted online, and some other user (not you) was using them to process their own locally-stored files.
MDN has a good tutorial on how to get started with <input type="file"> inputs.
The code won't work locally due to cross-origin limitations.
It works fine when run on a remote server and all files are in the same folder.
If you want to read local files (aka. files selected by user through the file input) you can read more about FileAPI here:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
I've already tested this code manually adding the backslash to all the </script> tags, and
if all the tags become <\/script> the code works.
var iframe = document.createElement('iframe');
var html = '<html><head><script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"><\/script><script type="text/javascript">$(window).load(function(){function popo1(){alert("ciaoooo!");}popo1();$(".eccolo").html("<br><br><br><br>xD sygsyusgsuygsus ysg usygsuys");});<\/script></head><body><div class="eccolo"></div></body></html>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
DEMO
But I need to dynamically auto-replace all the </script> tags with <\/script> using something like
XXX.replace(/<\/script>/ig, "<\\\/script>");
according to this post
but seems that this type of replace is actually not working...
var iframe = document.createElement('iframe');
var XXX = '<html><head><script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"><\/script><script type="text/javascript">$(window).load(function(){function popo1(){alert("ciaoooo!");}popo1();$(".eccolo").html("<br><br><br><br>xD sygsyusgsuygsus ysg usygsuys");});<\/script></head><body><div class="eccolo"></div></body></html>';
var YYY = XXX.replace(/<\/script>/ig, "<\\\/script>");
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(YYY);
iframe.contentWindow.document.close();
DEMO
Unfortunately I can't use .js files, so I hope that there is a way to properly do the tags replace
But what if I want to dynamically replace all the </script> tags with <\/script>...
In a comment below, you've said:
I'm getting the var XXX from an input that always changes.. I just added a defined value (var XXX='<html><head>...) in my question just for example
That's a very different thing than what's in your question. If you're saying that you'll receive input in the XXX string whose content (in memory, not a string literal) looks like this:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(window).load(function() {
function popo1() {
alert("ciaoooo!");
}
popo1();
$(".eccolo").html("<br><br><br><br>xD sygsyusgsuygsus ysg usygsuys");
});
</script>
</head>
<body>
<div class="eccolo"></div>
</body>
</html>
...then than input is perfectly fine and can be used as-is to set the content of the iframe. You don't have to do the replacement on it. The post you linked to doesn't relate to what you're doing.
But if you're saying you'll get input like this:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(window).load(function() {
var str = "The problem is here: </script>"; // <======
});
</script>
</head>
<body>
<div class="eccolo"></div>
</body>
</html>
...then you're in the same unfortunate position as the HTML parser: You don't know when the substring </script> actually ends a script element, or is text within a JavaScript string literal (or a comment). If you had a web page with that content, the HTML parser would conclude the script element ended immediately after The problem is here:. And indeed, if you output that content to an iframe via document.write, the parser will choke on it. The line:
var str = "The problem is here: </script>";
needs to be
var str = "The problem is here: <\/script>";
// or
var str = "The problem is here: </sc" + "ript>";
// or similar
...in order to avoid tripping up the HTML parser. (It would be fine in a .js file, but that's not your use case.)
Fundamentally, if you're receiving input with something like that in it, the person giving it to you is giving you invalid input. The substring </script> cannot appear in JavaScript code within <script>/</script> tags — not in a string literal, not in a comment, nowhere.
The answer defined by the spec is: Don't try to figure it out, require that it be correct. But if you know the scripts are JavaScript, and you really really want to allow invalid input and correct it, you'll need a JavaScript parser. That sounds outrageous, but Esprima is exactly that, there's jsparser in the Meteor stuff, and there may be others. You'd scan the string you're given to find <script>, then let the JavaScript parser take over and parse the code (you'll probably need to modify it so it knows to stop in </script> outside of a string literal / comment). Then take the text consumed by the parser, use your replace to convert any </script> in the code's text to <\/script>, and continue on.
It's non-trivial, which is why the spec doesn't require HTML parsers to do it.
But again, if the input is like your example in your question (without the backslashes you used to avoid this problem with your string literal), you don't have to do a replace at all. Just output it to the iframe, and it will work fine.
You can create script tag programatically and append in the head tag after page is loaded.
Following is the code and DEMO
var iframe = document.createElement('iframe');
var html = '<html><head></head><body><div class="eccolo"></div></body></html>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
var script1 = iframe.contentWindow.document.createElement('script');
var script2 = iframe.contentWindow.document.createElement('script');
script2.textContent = '$(window).load(function(){function popo1(){alert("ciaoooo!");}popo1();$(".eccolo").html("<br><br><br><br>xD sygsyusgsuygsus ysg usygsuys");});'
var head = iframe.contentWindow.document.querySelector('head');
head.appendChild(script1);
script1.onload = function() {
head.appendChild(script2);
}
script1.src = 'http://code.jquery.com/jquery-1.11.0.js';
iframe.contentWindow.document.close();
Hope it helps...
UPDATE 1
Here is how I am currently loading text into my WT project.
wApp->require("ace.js");
//orignal XML, reads in incorrectly on one line
//std::string data = ReadFile("Q:\\settings.xml");
//XML after being formatted in notepad to look like xml, reads in correctly
//std::string data = ReadFile("Q:\\settings.txt");
//changed extension back to XML, edited in notepad++ to XML format, reads in correctly
std::string data = ReadFile("Q:\\settings_from_text.xml");
//test xml tag, reads in correctly
//std::string data = "<tag_1>some tag content</tag_1>";
//test xml tag with newline, reads in incorrectly on one line, doesnt read newline
//std::string data = "<tag_1>some tag content</tag_1>\n<tag_1>some tag content</tag_1>";
_ace_editor = new WText(data, Wt::PlainText);
//_ace_editor->setText(data);
_ace_editor->setInline(false);
// A WContainerWidget is rendered as a div
_ace_editor->resize(1000, 500);
std::string editor_ref = _ace_editor->jsRef(); // is a text string that will be the element when executed in JS
std::string command =
editor_ref + "._ace_editor = ace.edit(" + editor_ref + ");" +
editor_ref + "._ace_editor.setTheme(\"ace/theme/chrome\");" +
editor_ref + "._ace_editor.getSession().setMode(\"ace/mode/xml\");";// +
//editor_ref + "._ace_editor.setValue(\"" + data + "\");";
_ace_editor->doJavaScript(command);
Also, here is the ReadFile function
std::ifstream in(path, std::ios::in | std::ios::binary);
if(in)
{
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
throw(errno);
ORIGINAL POST
I am trying to load some XML files into an Ace (http://ajaxorg.github.io/ace/#nav=about) editor that I embedded in a WT (http://www.webtoolkit.eu/wt?wtd=rqBfShGlNupXgK3M1sWOxUk1Loz3BsW0) page. The problem is that XML files for whatever reason have all their tags omitted from the load. Example: An XML file with the following content
<?xml version="1.0"?>
<settings>
<tag_1>some tag content</tag_1>
<tag_2/>
</settings>
will be loaded as
some tag content
I need the entire XML file as is, not just the contents of the tags.
After doing a bit of research, I have found quite a few other people on different forums asking the same thing but everything I have tried so far has not been working, which brings me here.
This includes setting the Ace mode to XML, trying to load the text in a different container before setting it to the ace window, changing the color schemes, and parsing a file in a different manner.
I am using visual studio 2010, and from debugging I can see that the file does get read in fully into a string with all the tags, but after it is set to the Ace window they are omitted.
Regardless of whether you are putting it on a WT page or not, bottom line this is a javascript question as that is what the ACE editor is, a javascript tool. Since you have not shown anything at all about how you are loading the xml content, I can only speculate that you must be writing the contents of the xml file into the pages output source?? I'll bet if you view-source do you see the tags? Well if so you are going about it wrong. The xml file needs to be loaded via javascript/ajax as I will demonstrate with a fully working example below (edit the 'url' in the $.ajax call to location of an xml file on your server), which shows tags and all contents of the xml file. Added the jQuery library just for simplicity of the ajax request code. Enjoy!
<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<style type="text/css" media="screen">
#editor {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
</head>
<body>
<div id="editor"></div>
<script src="http://rawgithub.com/ajaxorg/ace-builds/master/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
var callback = function (data, status, xhr) {
//data will be the xml returned from the server
if (status == 'success') {
var editor = ace.edit("editor");
//apparently, only modes supported are 'html', 'javascript' & 'text'
editor.getSession().setMode("ace/mode/html");
editor.setValue(data);
}
};
//using jQuery to fire off an ajax request to load the xml,
//using our callback as the success function
$.ajax(
{
url : '/testing/cd_catalog.xml',
dataType : 'text', //explicitly requesting the xml as text, rather than an xml document
success : callback
}
);
</script>
</body>
</html>
Actually, I take back some of what I said about the "must load via javascript/ajax", as I now realize you were just following ACE's example of putting the contents into the editor div beforehand. If you want to do that with html or xml content, the tags will be evaluated by the browser and not show up, unless you copy the editor div's innerHTML then instantiate the editor and then set it's value to the previously saved innerHTML. For example:
<div id="editor"><?xml version="1.0" encoding="ISO-8859-1">
<books>
<text>some text content</text>
<book/>
</books></div>
<script src="http://rawgithub.com/ajaxorg/ace-builds/master/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var txt = document.getElementById('editor').innerHTML;
var editor = ace.edit("editor");
//editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/html");
editor.setValue(txt);
</script>
XML fragments in XML... you can somehow expect that your browser will interpret them, unless properly escaped. Try this:
txt = new WText("<bla>something</bla>", Wt::PlainText);
which will escape all XML-ish characters in your text.
Wt's default (XHTMLText) will try to parse your input as XML, and if it succeeds filter possible XSS vectors from the XML before sending it as XML to the browser. If it can't parse the text as XML, it will escape XML-ish characters to avoid that a browser with a liberal parser would unintentionally execute attack vectors.
The third option (XHTMLUnsafeText) bypasses XSS filtering - dangerous, so only use it when you know that your text is safe and can not be influenced directly or indirectly by the user.
I have in my application layout file an external javascript file witch has several lines of code and at the end runs a function like BooManager.init() no big deal...
the problem is, it is not running the inside code on this javascript file.
this is how i use it:
<script type="text/javascript">
bb_bid = "1615455";
bb_lang = "en-US";
bb_keywords = "iphone4s, apple";
bb_name = "custom";
bb_limit = "8";
bb_format = "bbb";
</script>
<%= javascript_include_tag "http://widgets.boo-box.com/javascripts/embed.js" %>
but it didn`t do anything it was suposed to do...
i`ve tried in simple html file and it works... what am i doing wrong?
NOTE:
the default way in html is this:
<script type="text/javascript">
bb_bid = "1615455";
bb_lang = "en-US";
bb_keywords = "keywords, between, commas";
bb_name = "custom";
bb_limit = "8";
bb_format = "bbb";
</script>
<script type="text/javascript" src="http://static.boo-box.com/javascripts/embed.js"></script>
-- EDIT --
the result generated by rails:
<script type="text/javascript" src="http://static.boo-box.com/javascripts/embed.js"></script>
It's not evaluating the script when loading using the <%= method. I'm not familiar with that syntax, but from the effect, that's what it sounds like. It's treating the script as html rather than code.
jQuery has a script load function that will get a script dynamically from a URL and then eval() it to execute it.
UPDATED WITH SAMPLE CODE
Add jQuery to your app:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
Then use it to load your script:
$.getScript('http://widgets.boo-box.com/javascripts/embed.js');
UPDATE NUMBER 2
I was able to duplicate the problem in this fiddle: http://jsfiddle.net/7x2zT/4/
If what you are trying to accomplish is to get your parameters activated before the script shows the widget - the default one looks like a sidebar, whereas your parameters make it more of a banner, then just make sure you put your parameters above the <script src stuff.
If you must be able to load dynamically, then you're going to have to figure out where the bug lies in the embed code, or if there's some other activation method. That site's documentation doesn't seem to be in English, so I can't help with that.