How to avoid function overrides in dart html (dart web)?

Issue

Let’s say I call window.alert('my message') in dart code. But what if (exactly my case) there is a script which did override alert function before my script. Now if I try to call window.alert('message') It executes overridden alert function instead of initial one.

Is there a mechanism to ensure that all functions are not overridden in described way? Or should I always make sure that dart script is the first to execute on page to ensure that no undesirable overrides are done and behavior is stable and it’s the only way to go?

Here is basic github repo if you would like to see the issue live.

EDIT 1:

main.dart

import 'dart:html';

void main() {
  window.alert('alert');
}

index.html

<html>
<head>
    <title>test</title>
    <script>
        alert = (variable) => confirm("hehe it's jinxed");
    </script>
    <script defer src="main.dart.js"></script>
</head>
</html>

Solution

That does not sound possible.

If something "overrides" the JavaScript alert function, it actually overwrites the alert property of the window object. The old value is completely lost at that point, and it’s not (easily) possible to even detect that this has happened.

If your code doesn’t run first in a web browser, you can’t protect yourself from this. If your code does run first, you can use Object.freeze or similar functionality to lock down the original properties, or take copies of them into your own variables. Simply running first is not a guarantee, if your code just uses window.alert directly later. You have to make an effort to prevent later code from overwriting it too.

This is really a JavaScript issue, there is nothing special about dart:html or Dart compiled code in this, it affects any JavaScript code which doesn’t run first in a browser.

Answered By – lrn

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *