Is it possible to prevent JavaScript alert|confirm|prompt from popping up in UIWebView before the rendering process is finished?

Several questions have been asked on SO regarding similar issues, but none have addressed my specific question. Many of the answers suggest running a JS snippet that overloads the alert method, like this: window.alert = function() {};

The issue I am facing is that a webpage (whose content I cannot control) triggers an alert before the entire page has finished rendering.

Due to this, I am unable to utilize the

- (void)webViewDidFinishLoad:(UIWebView *)webView
delegate method to execute the JS snippet. Running the snippet in
- (void)webViewDidStartLoad:(UIWebView *)webView
also doesn't help because it runs before the DOM is loaded.

Related questions:

  • Capture (and prevent) alert() modal in UIWebView
  • Can I handle alert inside UIWebViewDelegate?
  • UIWebView: Can I disable the javascript alert() inside any web page?

Any suggestions on how to approach this problem?

Answer №1

After testing different methods for injecting Javascript, I decided to go back to using the native platform.

By utilizing a UIWebView, which automatically converts Javascript alerts into native UIAlertViews, I was able to easily block them on the native side. By examining UIAlertView.h, I found that there is only one public method for displaying an alert, appropriately named: - (void)show;.

To achieve this, I created a category in order to avoid potential issues with subclassing UIAlertView as mentioned in the documentation.

@interface UIAlertView (Blocker)
@end

#import "UIAlertView+Blocker.h"

@implementation UIAlertView (Blocker)

- (void)show {
   return;
}
@end

By importing this category into the view controller containing the UIWebView, all instances of UIAlertView and consequently all JS alerts are blocked.

I believe this solution is more reliable as it does not involve manipulating Javascript, altering HTML, or relying on external libraries. It is also not dependent on where the JS-alert code is located within the web content.

Answer №2

It appears that the outcome could differ depending on the rendering engine being used. In my experience, the following approach seemed to be effective:

alert("something");
alert = function(){};
alert("awesome");

http://jsfiddle.net/g5S5M/ I am aware of the differences in engines such as V8 used by Chrome compared to Firefox or IE. Therefore, when developing complex web applications, careful consideration is needed as browsers may interpret JavaScript differently.

Consider looking into third-party libraries that might override this function. If you encounter conflicts where one script makes alert blank and another reinstates it, you may need to remove or adjust the library or alter their execution order.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery selectors to assign a value to a particular text input field with a matching name

Is it possible to set only the file name field that matches each file input field? I have three text input fields with the same name and three text fields for the file names. function getFileData(myFile){ var file = myFile.files[0]; var filename = ...

How to transform an array into a collection of objects using React

In my React project, I encountered the following data structure (object of objects with keys): const listItems = { 1:{ id: 1, depth: 0, children: [2,5] }, 2:{ id: 2, depth: 1, children: [3,4], parentIndex: 1, disable ...

Is it possible to dynamically alter a CSS property using styled components when an onClick event occurs?

Hey there, I'm pretty new to React and currently exploring styled components for the CSS styling of my components. One of the components I've created is a button called SummonButton: const SummonButton = styled.button` height: 50px; borde ...

Having trouble getting my scene to scroll horizontally on its own

I am currently working on developing a game where the main character, or "hero," runs endlessly and must navigate through obstacles to earn points. I am using Sprite Builder to create this game, however, I am still learning and struggling with the coding a ...

Attempting to populate getElementByID using JavaScript function from CodeBehind proves unsuccessful

When a button is clicked on a form, I need to fill in hidden elements that will be posted. The script below should set the values for these hidden fields: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> < ...

Unable to convert value to ObjectID

I am receiving an array of names (String) in my body and I want to convert each name to its corresponding object ID from my Collection. My goal is to reference Strings to a Schema and replace them with their ObjectIds. This is the Schema I am using: ...

The Angular 2 rollup AoT compilation results in a larger build size compared to the standard JiT build

I'm facing an issue with reducing the weight of my app during the building process. I am using Angular 2 seed as a starting point. https://github.com/mgechev/angular-seed When I run: npm run build.prod my app.js file size is 1.5MB. However, when I ...

Changing a variable in an HTML file using a JavaScript file

I am working with JavaScript code that has been imported from another file containing a variable that I need to update in my HTML file. Is there a way to update the variable without directly inserting the JavaScript code into my HTML document? JavaScript ...

Having trouble with nested requests and appending using Jquery or JavaScript?

Greetings everyone, I want to apologize in advance for any spelling errors or mistakes in my message. I struggle with dyslexia and other learning difficulties, so please bear with me. I am using this time during lockdown to learn something new. This is my ...

Utilizing JSON schema for rendering React components

Experimenting with dynamically rendering React components using JSON, I have a folder structure organized as follows: components Foo.jsx Bar.jsx index.js App.jsx The index.js file contains the code for exporting all components as strings for uti ...

ESLint's feature experimentalObjectRestSpread not being applied with expected behavior

ESLint is showing an unexpected token error, specifically error Parsing error: Unexpected token .., and I'm struggling to identify the root cause. In my .eslintrc.js file, I have: module.exports = { extends: "devmountain/react-config" , rul ...

Retrieve this from a separate React Native class

Currently, I am refactoring my code to eliminate the repetition of lines by creating a Functions.js file that allows me to call functions from other classes. However, I am facing an issue where I cannot execute the function while maintaining the properties ...

Record collection of elements - JavaScript Angular

I am facing an issue with my page code. The code contains a list of items and I need to extract the values of Test, Application, Success, Error from these items. However, when I try to write this data to a file, it returns [object, Object]. Can someone ple ...

What is the method of duplicating an array using the array.push() function while ensuring no duplicate key values are

In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the ...

Is there a way to locate a specific property within a mongoose model using a different property?

In my mongoose schema, I have defined the following properties: var personnelSchema = new Schema({ fullName: String, dob: String, cNumber: String, address: String, wCard: String, dLic: Number, ...

experiencing deployment issues with the openai npm package

I encountered an unexpected error in my backend while trying to deploy. This error only started appearing after I installed the openai package. Although my node version is 20, which should support node:fs, it seems that the module 'node:fs' cann ...

A translucent modal view controller extending below the tab bar in a Swift application

I tested the code provided in this gist: https://gist.github.com/barbietunnie/e5547f35180436ac102cac52a15f8ca3 func showModal() { let modalViewController = ModalViewController() modalViewController.modalPresentationStyle = .OverCurrentContext ...

Is it true that document.execCommand only works with buttons and not links?

Below is the code snippet I am working with: <div contenteditable="true" style="height:100px;width:100px;border:1px solid; " class="editor"></div> <a class='bold' style="height:10px;width:10px;">B</a> $(function(){ ...

Tips for incorporating css styles and javascript into handlebar files

I've been trying to figure out how to add styles and js to my handlebar files, but I'm hitting a roadblock. I attempted to use partials to store the stylesheet tags and then include those partials in the handlebars file, but it didn't work a ...

Challenges arise when attempting to modify an ArrowHelper without creating a new instance

In my project using three.js, I am facing a challenge with updating the components of 3 ArrowHelper. Currently, I am able to update these 3 ArrowHelper in my animation by creating new instances each time the drawing function is called. For instance, in my ...