SRy
SRy

Reputation: 2967

onclick in jsf commandbutton is not working in chrome

I am invoking JavaScript in <h:commandButton> by onclick event.

 <h:commandButton type="submit" 
          value="Next" action="#{bean.save}"    
          onclick="javascript:getHtml();"/>

 function getHtml(){
      document.getElementById('source').value="HTML source of the page";

  }

output HTML for commandButton in IE/Firefox

<input id="Form:submit" name="Form:submit" 
           type="submit" value="Next"
           onclick="var cf = function(){getHtml();};var oamSF = function(){return 
myfaces.oam.submitForm('Form','Form:submit',null,[['sample','sample']]);};return (cf.apply(this, [])==false)? false : oamSF.apply(this, []);">

But in chrome I see the below JavaScript error with the below HTML

Refused to execute a JavaScript script. Source code of script found within request.

<input id="Form:submit" name="Form:submit" 
       type="submit" value="Next" 
       onclick="" >  // onclick is empty

when i went through forums I see this is to prevent against Cross site scripting when there is onclick with POST as explained in this question

Refused to execute a JavaScript script. Source code of script found within request

This happens when some JavaScript code is sent to the server via an HTTP POST request, and the same code comes back via the HTTP response. If Chrome detects this situation, the script is refused to run, and you get the error message Refused to execute a JavaScript script. Source code of script found within request.

How can i Fix this ? I am using JSF 2.0 with Apache myfaces implementation.

Upvotes: 1

Views: 10096

Answers (1)

Daniel
Daniel

Reputation: 37061

How about

<h:commandButton type="submit" 
      value="Next" action="#{bean.save}"    
      onclick="document.getElementById('source').value='HTML source of the page'; 
      return false;"/>

If this works for you than you didn't include or placed your js file properly in your page / project ...


A better solution would be to properly include your js file

like this

<h:outputScript name="js/myFile.js" target="head"/>

Place your myFile.js inside WebContent\resources\js

Than use it like this

<h:commandButton type="submit" 
      value="Next" action="#{bean.save}"    
      onclick="getHtml(); return false;"/>

Upvotes: 2

Related Questions