Cannot access javascript function in ADF InlineFrame - javascript

I have a jsff page containing af:InlineFrame.
The source of this InlineFrame is HTML file say Frame.html
This html file has a javascript function called inlineframeFunction()
I have a button added in the jsff page.
My usecase is to invoke the function inlineframeFunction on click of the button which i am not able achieve.
var doc = inlineFrame.contentDocument?
inlineFrame.contentDocument: inlineFrame.contentWindow.document;
doc.frameFunction();
Frame.html
<script type="javascript">
function inlineframeFunction(){
alert('Inline Frame Function ');
}
</script>
JSFF Page
<af:panelGroupLayout id="pgl1" layout="vertical">
<af:resource type="javascript">
function inlineFrameRegionPageFunction() {
alert('Region Page Function');
var inlineFrame = document.getElementById('r1:0:if2');
var doc = inlineFrame.contentDocument? inlineFrame.contentDocument: inlineFrame.contentWindow.document;
doc.frameFunction();
}
</af:resource>
</af:panelGroupLayout>
<af:panelGroupLayout id="pgl2" layout="vertical">
<af:panelBox text="Inline Frame Region" id="pb2"
inlineStyle="background-color:Lime; border-color:Lime;">
<f:facet name="toolbar"/>
<af:inlineFrame id="if2" source="/Frame.html" shortDesc="InlineFrame"
inlineStyle="background-color:Gray;"/>
<af:commandButton text="Inline Region Button" id="rb2"
actionListener="#{pageFlowScope.RegionBean.onClickInlineFrameRgnButton}"/>
</af:panelBox>
</af:panelGroupLayout>

I used the following and it worked!
function inlineFrameRegionPageFunction() {
var frameComp =$('[id*="InlineFrame"]', document)[0].id;
document.getElementById(frameComp).contentWindow.frameFunction();
}
</af:resource>

To execute a javascript from a managed bean in adf you can use the following function (https://cedricleruth.com/how-to-execute-client-javascript-in-an-adf-java-bean-action/) :
/*** In YOURJSF.jsf button, or other component that need to execute a javascript on action, add : ****/
<af:commandButton text="ClickMe" id="cb1" actionListener="#{YOURSCOPE.YOURJAVABEAN.clickToExecuteJavascriptAction}"/>
/*** In YOURJAVABEAN.java class add : ***/
public void clickToExecuteJavascriptAction(ActionEvent actionEvent) {
this.executeClientJavascript("console.log('You just clicked : " + actionEvent.getSource() + " ')");
//Note: if you use a java string value in this function you should escape it to avoid breaking the javascript.
//Like this : stringValue.replaceAll("[^\\p{L}\\p{Z}]", " ")
}
//You should put this function in a util java class if you want to use it in multiple bean
public static void executeClientJavascript(String script) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExtendedRenderKitService service = Service.getRenderKitService(facesContext, ExtendedRenderKitService.class);
service.addScript(facesContext, script);
}
Then in your case, refer to this question to call your iframe js function using javascript inside your action listener (Calling javascript function in iframe)
document.getElementById("if2").contentWindow.inlineframeFunction();

Related

Accessing java variable from javascript in spring mvc

i am relatively new to spring mvc.what i am trying to do is pass a variable as model attribute and try and access it on page load with javascript on my JSP page.
my java code is as follows
model.addAttribute("leagueCode",leagueCode);
model.addAttribute("league","new");
return "redirect:/Dashboard";
and on jsp side i am trying to access it by following
<script type="text/javascript"> function myFunction() { var leagueCode=${leagueCode}; alert(leagueCode); } </script> </head> <body onload="myFunction()">
but i am getting the value as blank. is this the right way i am following or is there any other way this has to be done? please help
In the JSP page you can set the values as javascript variables by adding a script tag in the <head> with the assignment inside as a json object for example:
<script>
var myServerSideVars = {
"aServerSideVarName" : "<here you set the value with el/jslt/scriptlet>",
"anotherServerSideVarName" : "<here you set the value with el/jslt/scriptlet>"
};
</script>
EDIT I
Example using EL (Expression Language) but the same could be done with scriptlets if you are using that (<% %>):
Lets say in your Servlet you put a Car instance in the request before forwarding to the JSP page.
The car:
public class Car{
protected String brand;
protected String year;
//getters and setters for the two properties.
}
In the Servlet you put it into the request:
Car car = new Car();
car.setBrand("BMW");
car.setYear("2017");
request.setAttribute("carInRequest", car);
In the JSP you set it to a Json Object accessible from javascript. Before closing the body tag I put a simple example of how the var can be accessed from javascript. I haven't run it so it may have some typo or error to correct:
<%#taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>System.out.println</title>
<script>
var aCar= {
"brand" : "${requestScope.carInRequest.brand}",
"year" : "${requestScope.carInRequest.year}"
};
</script>
</head>
<body>
<h2>Brand: <span id="brandPlaceHolder"></span></h2>
<h2>Year: <span id="yearPlaceHolder"></span></h2>
</body>
<script>
var brandSpan = document.findElementById("brandPlaceHolder");
brandSpan.html = aCar.brand;
var yearSpan = document.findElementById("yearPlaceHolder");
brandSpan.html = aCar.year;
</script>
</html>

Activate javascript string onload on code behind C#

Good day!
I need a help on activating my javascript function via on-load on code behind.
Here is my code:
string script = #"var applyCss = function () {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
}; ";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "css", script, true);
By the way, my code above works in front-end via button click.
But my desired result is, I want my javascript function to work on page load without needing to click the button. I put my javascript function in code-behind because I will put dynamic dates in the css variables. The code above still has static variables. (CalendarPanel1-month-day-20170607)
Will gladly appreaciate any response / solution. Big thanks!
You could use an immediately invoked function to do the trick. Basically you don't give a name to your javascript function and you invoke it right after it's defined.
For example:
var script = #"(function () {alert('Hello');})(); ";
ScriptManager.RegisterStartupScript(this, typeof(Page), "123", script, true);
You need to wrap the function with its body between parenthesis then another set of parenthesis to invoke the function.
You can also pass parameters to your function (which I'm assuming it's what you want to do):
var myAlertText = "Hello Hello";
var script = #"(function (myText) {alert(myText);})('" + myAlertText + "');" ;
If I were you though I would defined the function in client code and just invoke it from code behind with the right parameters.
An alternative and fancier way to call javascript code from code behind would be using X.Call(). Check out this example:
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
string script = #"var myJSSideVar = 'my var value';
var applyCss = function (paramOne, paramTwo) {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
Ext.Msg.alert('applyCss called.', 'I\'ve been run with parameters: (' + paramOne + ', ' + paramTwo + ').');
};";
var hi = "hello";
X.AddScript(script);
X.Call("applyCss", new object[] { hi, new JRawValue("myJSSideVar") });
}
}
</script>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form runat="server" id="form1">
<div>
<ext:ResourceManager runat="server" />
</div>
</form>
</body>
</html>
Notice the second parameter sent to the script call is sent "raw", i.e., it calls: applyCss("hello", myJSSideVar)
If you need to pass but one single parameter you don't need to pass an array, e.g. X.Call("applyCss", hi);

JS code not executed

I'm currently trying to call a JS script in order to export chart from primefaces chart component.
The problem is that the base64str variable seem to be null, and the responsible script for filling this value is not called for some reason :
xhtml code :
<p:chart id="chart" type="line" widgetVar="chart" model="#{cont.lineModel}" style="height:550px;width:1800px">
<p:ajax event="itemSelect" listener="#{cont.itemSelect}" update="growl" />
</p:chart>
<p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
onclick="exportChart();" actionListener="#{cont.submittedBase64Str}"
/>
<h:inputHidden id="b64" value="#{cont.base64Str}" />
<script type="text/javascript">
function exportChart() {
img = chart.exportAsImage();
document.getElementById('hform:b64').value = img.src;
}
</script>
Controller :
public void submittedBase64Str(ActionEvent event){
// You probably want to have a more comprehensive check here.
// In this example I only use a simple check
if(base64Str.split(",").length > 1){
String encoded = base64Str.split(",")[1];
byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(encoded);
// Write to a .png file
try {
RenderedImage renderedImage = ImageIO.read(new ByteArrayInputStream(decoded));
ImageIO.write(renderedImage, "png", new File("D:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks
Change your onclick attribute to onstart.
<p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
onstart="exportChart();" actionListener="#{cont.submittedBase64Str}" />
That should call the JS function.
EDIT
Also, you need to define img and chart in your function.
chart object is the PrimeFaces JS widget. You define widgetVar:
<p:chart ... widgetVar="chart"
And then you can get the chart object in your JS code like this:
PF('chart')
You need to use the PF function to get widgets since PrimeFaces 4.0.
As a side note, it's better to make your img variable local instead of global:
var img = chart.exportAsImage();
Now img is defined only in the scope of the function.

SharePoint 2010: Create a bookmark button that adds a page to your My Links

I am trying to create a link/button on my masterpage which when clicked, adds the current page to the user's My Links list. This is merely a shortcut to save the user from having to navigate to their My Site and add the link manually.
[This blog post] gives a solution to this problem, but I get a JavaScript error on the second line of the "Add Link" dialog (QuickLinksDialog2.aspx) because the frameElement property is null:
<script language="Javascript">
var form = document.forms[0];
var args = window.parent.frameElement.dialogArgs;
Regardless, Portal.js appears to contain all the functions that the My Links page (_layouts/MyQuickLinks.aspx) uses to add links to this list.
Can anyone suggest how I might go about calling one/some of these functions from my masterpage so that the "Add Link" dialog is opened with the title and URL fields pre-poulated?
I ended up using the object model to create the My Links (as apposed to the popup dialog).
The upside to this is that adding a link is now only a 1-click process, the downside is that the user does not have the opportunity to rename the link or assign it to a group (personally, I've hidden the groups from the UI anyway as we didnt need them so this was a non-issue for me).
For those interested, I created a little usercontrol which just houses an ajaxified button which you can drop onto your masterpage / page layout. My code for this is as follows:
HTML
<script type="text/javascript">
function FavouriteImageButton_AddMyLink_Clicked() {
SP.UI.Notify.addNotification("Bookmark generated successfully.");
}
function FavouriteImageButton_RemoveMyLink_Clicked() {
SP.UI.Notify.addNotification("Bookmark deleted successfully.");
}
</script>
<asp:UpdatePanel ID="UpdatePanel" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:ImageButton ID="FavouriteImageButon" runat="server" OnCommand="FavouriteImageButton_Command" />
</ContentTemplate>
</asp:UpdatePanel>
C#
private struct FavouriteButtonCommandNames
{
public const string AddMyLink = "AddMyLink";
public const string RemoveMyLink = "RemoveMyLink";
}
protected void Page_PreRender(object sender, EventArgs e)
{
// Initialise the favourites button according to whether or not the page already exists in the My Links list.
this.FavouriteImageButon.ImageUrl = "/_layouts/images/favourite_add.png";
this.FavouriteImageButon.AlternateText = "Add to My Links";
this.FavouriteImageButon.CommandName = FavouriteButtonCommandNames.AddMyLink;
this.FavouriteImageButon.CommandArgument = null;
UserProfileManager userProfileManager = new UserProfileManager(SPServiceContext.Current);
UserProfile currentUser = userProfileManager.GetUserProfile(false);
foreach (QuickLink quickLink in currentUser.QuickLinks.GetItems())
{
if (quickLink.Url.ToLower() == this.Page.Request.Url.ToString().ToLower())
{
this.FavouriteImageButon.ImageUrl = "/_layouts/images/favourite_delete.png";
this.FavouriteImageButon.AlternateText = "Remove from My Links";
this.FavouriteImageButon.CommandName = FavouriteButtonCommandNames.RemoveMyLink;
this.FavouriteImageButon.CommandArgument = quickLink.ID.ToString();
break;
}
}
}
protected void FavouriteImageButton_Command(object sender, CommandEventArgs e)
{
UserProfileManager userProfileManager = new UserProfileManager(SPServiceContext.Current);
UserProfile currentUser = userProfileManager.GetUserProfile(false);
switch (e.CommandName)
{
case FavouriteButtonCommandNames.AddMyLink:
// Create the link.
currentUser.QuickLinks.Create(
SPContext.Current.File.Title,
this.Page.Request.Url.ToString(),
QuickLinkGroupType.General,
null,
Privacy.Private);
// Display a notification message.
ScriptManager.RegisterStartupScript(this.UpdatePanel, this.UpdatePanel.GetType(), e.CommandName, "ExecuteOrDelayUntilScriptLoaded(FavouriteImageButton_AddMyLink_Clicked, \"sp.js\");", true);
break;
case FavouriteButtonCommandNames.RemoveMyLink:
long id;
if (long.TryParse((string)e.CommandArgument, out id))
{
// Delete the link.
QuickLink quickLink = currentUser.QuickLinks[long.Parse((string)e.CommandArgument)];
quickLink.Delete();
// Display a notification message.
ScriptManager.RegisterStartupScript(this.UpdatePanel, this.UpdatePanel.GetType(), e.CommandName, "ExecuteOrDelayUntilScriptLoaded(FavouriteImageButton_RemoveMyLink_Clicked, \"sp.js\");", true);
}
else
{
throw new ArgumentNullException("e.CommandArgument", "\"{0}\" is not a valid QuickLink ID. The QuickLink could not be removed from the list.");
}
break;
}
}
Add the following function to your master page:
function addlink(){
t=document.title;
u=escape(location.href);
var q = window.location.protocol + "//" + window.location.host + "/_vti_bin/portalapi.aspx?cmd=PinToMyPage&ListViewURL=" + u + "&ListTitle=" + t + "&IsDlg-1"; // + "&ReturnUrl=" + u;
location.href = q;
}
Then add your anchor tag:
<a href='javascript:addlink()'>Add this Page</a>

external interface

I have a calc function in java script that takes three integer parameters,
following is the AS3 code
import flash.external.ExternalInterface;
var para:Array = new Array();
send_btn.addEventListener(MouseEvent.CLICK, clickListener);
function clickListener(eventObj:Object ):void {
para.push(mean.text);
para.push(std.text);
para.push(points.text);
trace("click > " + para);
ExternalInterface.call("calc",para );
}
is this the right way of doing it and how do i get back 3 arguments back from the javascript and display them in flash?
In addition, you need to register your AS function so that it's available to the container:
ExternalInterface.addCallback("callFlash", myASFunction);
Then, from your container (JS), you call the AS function and pass whatever parameters you want to it.
<script language="JavaScript">
flashObject.callFlash(param1, param2, param3);
</script>
...
<object id="flashObject"...>
...
<embed name="flashObject".../>
</object>
Lastly, in AS3, you write the function that will be executed when the container "calls back":
function myASFunction(param1:String,param2:String,param3:String):void {
trace("\n Received call from JS: " + param1 + param2 + param3);
}

Categories

Resources