I have an Apex controller MyController
which calls a VisualForce page via PageReference
.
Here is my controller:
public with sharing class MyController {
@AuraEnabled
public String param1 { get; set; } // Define a property named param1
public static String callVfPage() {
String pageName = 'TimeZoneVFPage'; // Name of the Visualforce page
String pageUrl = '/apex/' + pageName;
PageReference pageRef = new PageReference(pageUrl);
pageRef.getParameters().put('param1', 'value1'); // Set parameters if needed
String pageContent = pageRef.getContent().toString();
String processedValue = extractValueFromHtml(pageContent);
return processedValue; // Return the extracted value
}
private static String extractValueFromHtml(String htmlContent) {
String processedValue = null;
Integer startIndex = htmlContent.indexOf('<span id="processedValue">');
Integer endIndex = htmlContent.indexOf('</span>', startIndex);
if (startIndex != -1 && endIndex != -1) {
processedValue = htmlContent.substring(startIndex + '<span id="processedValue">'.length(), endIndex);
}
return processedValue;
}
}
And here is my VisualForce page:
<apex:page controller="MyController" showHeader="false" sidebar="false"
applyHtmlTag="false" applyBodyTag="false" standardStylesheets="false"
docType="html-5.0" language="en-US" cache="true"
contentType="text/html" title="TimeZoneVFPage" id="thePage"
>
<body>
<apex:outputText value="{!param1}" id="param1" />
<span id="processedValue">Old Value</span>
</body>
<script>
window.onload = function() {
onPageLoad();
};
function onPageLoad() {
document.getElementById('processedValue').innerText = 'New Value';
}
</script>
</apex:page>
When I call my controller method callVfPage
using the execute anonymous window like this:
string output = MyController.callVfPage();
system.debug(output);
output
is always "Old Value" instead of the expected "New Value". This page works fine when I preview it and displays New Value. But here, I think the script tag is not executed when I call it from Apex, therefore it returns "Old Value".
Any ideas on how I can make the Apex wait for the script to execute in my VisualForce page?
UPDATE: Here's what I am trying to do: I want to update each Account's timezone based on their Billing Address. Now I could easily use some sort of API and use a HTTP callout to get the timezone, but instead of making many API calls, I figured I could use a JS library to pass the figure out the timezone from the Billing Address, e.g using MomentJs.
Another possible solution could be to have a static list of timezones and countries/cities, and figure out the timezone based on the Billing Address that way, but then I would need to update this list manually.