Concealing specific sections of HTML content in a webview on the fly

I've been experimenting with a proof of concept feature to implement the ability to conceal certain parts of a web page loaded in a webview, but I seem to be encountering some issues...

Within a UIWebview extension, I have something similar to this code snippet which is executed when the webview finishes loading:

    let dummyStyle = "var dummyStyle = document.createElement('style'); dummyStyle.innerHTML = 'div {display: none;}'; document.body.appendChild(dummyStyle); "

    let classToHide = "content"
    let jsHideString = "var e = document.body.getElementByClassName('\(classToHide)'); e.style = dummyStyle; e.style.display = 'none';"
    self.stringByEvaluatingJavaScriptFromString(dummyStyle + jsHideString)

The main issue appears to be (as determined using safari/chrome developer tools) that the document element does not possess a style property. Even if I manually assign it via console, it fails to update when set to e.style.display = 'none'.

In addition to locating the element by id or class, I aim to limit the assumptions made regarding the end user's web page.

Thank you for taking the time to read my inquiry!

Edit with operational solution:

    let classToHide = "content"
    let jsHideString = " " +
        " var e = document.body.getElementsByClassName(\"\(classToHide)\")[0];" +
        "e.style.display = \"none\";"

    let DOMContentLoadedNotification = " " +
        "var addL = function addListener(obj, eventName, listener) { " +
            "if (obj.addEventListener) { " +
            "alert('added listener');" +
            "obj.addEventListener(eventName, listener, false); " +
            "} else { " +
            "alert('attactch event');" +
            "obj.attachEvent(\"on\" + eventName, listener); " +
            "};" +
            "};" +

        "var completion = function finishedDCL() { " +
            "alert('finishedDCL');" +
            jsHideString +
            "};" +

        "if (document.readyState == \"complete\" || document.readyState == \"loaded\") { " +
                "alert('document already loaded');" +
                jsHideString +
            "} else {" +
                "alert('document not loaded');" +
                "addL(document, \"DOMContentLoaded\", completion()); " +
"};"

    print("Webview: \(self.stringByEvaluatingJavaScriptFromString(DOMContentLoadedNotification))")

Answer №1

Avoid creating a stylesheet and instead directly manipulate the DOM node's .style property.

To hide an element, use

nodeReference.style.display = 'none'

If you are encountering issues with the style property not working, it could be due to not waiting for the DOM to fully load. Be sure to listen for the DOMContentLoaded event.

Learn more about the DOMContentLoaded event here

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

Develop an array of unique objects with multiple dimensions, ensuring no duplicates are included

Seeking assistance for the following task: I am trying to create a new multidimensional array of objects based on an existing array of objects: [ {number:111, connectedNumber: 112, ...}, {number:112, connectedNumber: 111, ...}, {number:113, connectedNumbe ...

How can I implement a scroll functionality to navigate to the next item in a Vuetify v-carousel?

I'm currently working on a front page layout using the v-carousel component and I am looking to achieve automatic scrolling to the next item without the need for arrows or delimiters. How can I make this happen? Below is my current code: <template ...

Unable to access a function from a different controller within an AngularJS Ionic framework application

How can I trigger or call the callkhs function in the LihatKhsController from the KhsController? function KhsController($scope, $rootScope){ $scope.$emit('callkhs', {param:'test'}); } I am attempting to retrieve parameter values ...

Expanding the input focus to include the icon, allowing it to be clicked

Having trouble with my date picker component (v-date-picker) where I can't seem to get the icon, a Font Awesome Icon separate from the date-picker, to open the calendar on focus when clicked. I've attempted some solutions mentioned in this resour ...

Oops! Module './api/routers' not found

Hello, I hope everyone is doing well... Currently, I am working on developing a NextJS single-page web application. To create a custom server for NextJs, I am utilizing Express, MongoDB, and nodemon for hot reload functionality. Upon starting the server, ...

Having difficulty executing the playwright tests

Trying to execute the playwright test from the specified location results in a message prompting to run npm install -D @playwright/test before running the test. Despite having already installed playwright as a dev dependency, the test is still not being ex ...

Troubleshooting a Cache Issue in Your Next.js Application

Whenever I attempt to run 'npm run build', an error crops up that seems to be linked to the css and fonts. Unfortunately, I am unsure of how to tackle this problem. It's perplexing as the app functions perfectly fine in development mode. Th ...

Resolving the Issue of Jerky Graphics During HTML5 Canvas Animation

When animating a layer in canvas, the visual quality becomes uneven if there are additional layers present. You can see an example of this by clicking "RUN" on this fiddle: http://jsfiddle.net/Q97Wn/ If I modify this line: opts.percentageIndicator.clearR ...

"Encountered an error: File or directory not found while attempting to export a function

src/test.js module.exports.test = function() { const { readFileSync } = require('fs'); console.log(readFileSync('test.txt', 'utf8').toString()) } index.js const { test } = require('./src/test.js'); test(); ...

Tips for combining enable and disable properties in flatpickr.js?

I'm facing a challenge with using both the enable and disable properties in flatpickr.js. The enable property returns a range of dates that should be enabled, but I specifically want to disable certain days within that range, like weekends. datePicker ...

Displaying 'N/A' in the chart if the data is missing

I have a chart that displays data, but when data does not exist it shows "undefined%". https://i.sstatic.net/Fm3Tl.png Is there a way to remove the "undefined%" and simply display nothing on the graph if no data exists? Here is the code snippet: import { ...

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...

Selenium is encountering an issue where it is unable to automatically download files, as the download confirmation

While reviewing someone else's code, I encountered an issue with automatically downloading PDF files from a web page using selenium. Despite setting the browser.helperApps.neverAsk.saveToDisk property to the PDF mime type, I am still getting the fire ...

React Timer App: The setInterval function is being reset after each render operation

I'm currently working on a straightforward timer application that will begin counting seconds when a button is clicked. To implement this, I am utilizing react hooks. import React, { useState } from 'react' function Timer() { const [sec ...

Selecting radio buttons using Bootstrap and JavaScript

I'm interested in incorporating this bootstrap radio selection feature into my JavaScript code. For example, if option1 is true, I want to execute a specific action... How can I achieve this? <div class="alert alert-info" role="alert"> < ...

Styling CSS to place an image in between text and background coloring

As I try to replicate a happy accident of mine, which originally occurred during my first attempt at CSS: I was just randomly adding selectors when I stumbled upon this unique layout. However, as I proceeded with rewriting the file, I failed to save the o ...

Getting a specific element from an Ajax response may involve using JavaScript methods to target the desired

Within my PHP file, there are multiple HTML elements that I am fetching in an AJAX response. Currently, all these HTML elements are being returned in my drop area. How can I adjust the code to only retrieve a specific element, such as an image, like so: P ...

What steps can I take to add a horizontal scroll bar and view the entirety of my image?

<img src="the fake.png" width="3268" height="538" class="table" alt=""/> I have a large image that is getting cut off on the page. I need to add a horizontal scrollbar so I can view the entire image ...

Unexpectedly, Internet Explorer 11 is causing the "input" event to fire prematurely

While troubleshooting a JavaScript issue, I came across what seems to be a bug in Internet Explorer 11. I am reaching out here on StackOverflow for validation and to see if anyone else using IE11 can replicate this problem. The problem arises when the val ...

When I try to execute `npm start` on Ubuntu 16.04, I encounter npm errors

My Ubuntu 16.04 OS has node v7.10.1 and npm v4.2.0 installed. I encountered an error when trying to start npm or sudo start npm. Everything was working fine this morning, but now I'm getting errors. Can someone please help me troubleshoot this? npm E ...