What I’m trying to do:
I have embedded an iFrame into my Anvil app, in which there I need to add some javascript code after embedded the iFrame.
What I’ve tried and what’s not working:
I’ve tried running the JavaScript code from my anvil app, but the triggers never run, and I believe it needs to be embedded into the iFrame, and not run from the parent.
The code attached is the JS I need to run from the iFrame.
Code Sample:
// Retrieve the TinCan xAPI file
fetch('https://example.com/path/to/tincan-file.json')
.then(response => response.json())
.then(data => {
// Process the TinCan xAPI statements
let completionFlag = false;
data.forEach(statement => {
// Check for completion-related attributes
if (statement.verb.display['en-US'] === 'completed') {
completionFlag = true;
}
});
// Send completion flag to the parent window (Anvil app)
window.parent.postMessage({ completionFlag }, '*');
})
.catch(error => {
console.error('Error retrieving TinCan xAPI file:', error);
});
Do you control the source of the iframe? If so, include the Javascript in it originally.
If you’re trying to inject the Javascript into the iframe dynamically, you’ll run up against cross domain security issues. Imagine a hacker creating an iframe that goes to Paypal and injecting their own Javascript into it.
If you can describe what you’re trying to accomplish outside of the technique you’re trying to use to get there, maybe there are alternatives that don’t involve injecting Javascript into the iframe.
@jshaffstall Thanks for your reply!
I definitely hadn’t considered that! Makes a lot of sense though!
I do control the source of the iframe, although with the use it would be rather tedious.
The system I’m trying to make is a learning management system where students can complete online courses. The courses are stored as TinCan xAPI currently, but other file types, like SCORM 1.2 and raw html are available. When a course is created, I’m unsure whether the JS can be added through Articulate RISE, the software used to create the courses, so potentially the html would need to be amended for every course that’s created, doable, but tedious! Hence the idea to look for a simpler more streamline solution.
Let me know if there’s any other information that may be needed!
If you’re serving the iframe source from the same domain as your Anvil app is on, then you’ll probably be able to inject Javascript into it (the browser shouldn’t trigger on any cross domain issues). I don’t specifically know how to do that, but there shouldn’t be anything Anvil specific in it.