I am working in a form in power apps and I'm having trouble passing form context to my HTML web resource consistently. It works sometimes, but most often (especially when people are looking) the web resource is unable to access the formcontext through window._formContext.
I have a button in my model driven app that on click needs to fetch a value from another form section and open an external website based on this value, and so I need to be able to access it. For setting the context, my html web resource is placed inside a section in a tab in a (power apps) form, and needs to access a value from a field in another section.
My code looks as follows: The OnLoad function is run when the form loads, and passes the formContext to the web resource. This works every time (and can be found in numerous examples online).
function OnLoad(executionContext){
const formContext = executionContext.getFormContext();
const webResourceControl = formContext.getControl("webResourceControl");
if (webResourceControl) {
webResourceControl.getContentWindow()
.then(function (contentWindow) {
contentWindow.setClientApiContext(Xrm, formContext);
});
}
}
My html-web resource (simplified) looks like this:
<script>
function setClientApiContext(xrm, formContext){
window.Xrm = xrm;
window._formContext = formContext;
}
function OpenWebsite(){
const attribute = window._formContext.getAttribute("new_examplename");
// ... more code but irrelevant
}
</script>
<body>
<button id="openButton" onClick="OpenWebsite()">Open website </button>
</body>
I define the setClientApiContext-function, the function to be run on button click that fetches an attribute, and the html button. When OpenWebsite is run, it is sometimes able to access _formContext. Other times, it returns
TypeError: Cannot read properties of undefined (reading 'getAttribute')
at OpenWebsite
Does anyone here know how to make it consistently work, or if there is anything I need to change? I am not able to figure out how to fix this.
note: I am new to power apps which is probably a large factor to why I am struggling. I know there are other approaches to creating buttons, but I have limited time and knowledge. If what I am attempting to do is impossible, please do tell :)