Recently, I published a blog post addressing similar issues that I encountered.
In the post, I started by discussing important prerequisites like Verifying CORS Compliance and Verifying JSONP Support.
Afterward, I implemented the updated method as follows:
window.onMessage.listen(dataReceived);
To dynamically create the script tag in Dart exclusively without altering the website source files, I utilized a simple method such as:
void _createScriptTag()
{
String requestString = """function callbackForJsonpApi(s) {
s.target="dartJsonHandler";
window.postMessage(JSON.stringify(s), '*');
}""";
ScriptElement script = new ScriptElement();
script.innerHtml = requestString;
document.body.children.add(script);
}
I then called this method from Dart with additional logic arranged within another convenient method.
void getStockQuote(String tickerId)
{
String requestString = "http://finance.yahoo.com/webservice/v1/symbols/" + tickerId + "/quote?format=json&callback=callbackForJsonpApi";
ScriptElement script = new ScriptElement();
script.src = requestString;
document.body.children.add(script);
}
If utilizing dart:js, you might find Alexandre's Answer helpful, and I have also integrated the simplified version into my post:
context['callbackForJsonpApi'] = (JsObject jsonData)
{
//Process JSON data here...
};
This streamlined approach removes the necessity for using onMessage
or _createScriptTag
and can be executed similarly to the previous method.
Despite adopting the newer methodology, I opted to maintain both approaches due to the evolving nature of Dart APIs, providing a fallback option if required.