Can stringByEvaluatingJavaScriptFromString be utilized with JavaScript that makes references to local files?

    

I am looking to implement stringByEvaluatingJavaScriptFromString in order to execute a JavaScript code that accesses local files (such as CSS or JS files) stored on the device (presumably in the Documents folder)...

 NSString *theJS = [[NSString alloc]
 initWithString:@"javascript:(function()
{the_css.rel='stylesheet';
the_css.href='the_css.css';
the_css.type='text/css';
the_css.media='screen';}
)();"];

[webView stringByEvaluatingJavaScriptFromString:theJS];

How can I make this work effectively? The function works perfectly when referencing an external CSS file, like

the_css.href='http://www.website.com/the_css.css';

Answer №1

In my previous experience, I have utilized the following code snippet while loading HTML content:

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:bundlePath];

[webView loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8 " baseURL:baseURL];

By passing the bundle location as the base URL, it ensures that relative URLs function correctly within your HTML content. While you are not restricted to using this specific loadData method, incorporating the baseURL component is essential for seamless operation.

If all other methods fail, an alternative approach involves utilizing something like:

NSString *path = [[NSBundle mainBundle] pathForResource:@"file.css" ofType:nil]]

You can then inject this information into the page using string replacements or a similar technique, albeit with a slightly unconventional workaround.

Answer №2

This is the recommended way to accomplish the task.

NSString *cssPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"the_css.css"];
NSURL *baseURL = [NSURL fileURLWithPath:cssPath];


 NSString *theJS = [[NSString alloc]
 initWithFormat:@"javascript:(function()
{the_css.rel='stylesheet';
the_css.href='%@';
the_css.type='text/css';
the_css.media='screen';}
)();",baseURL];
[cssPath release];

[webView stringByEvaluatingJavaScriptFromString:theJS];

Hopefully, this method will provide a solution to the issue at hand.

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

Combining a string-based array in JavaScript

I need to remove an item from a string indexed array. Take a look at this sample code: var arr = new Array(); arr[0] = "Zero"; arr[1] = "One"; arr[2] = "Two"; arr.splice(1, 1); for (var index in arr) document.write ...

Automate Zoom join function with the help of puppeteer

Having trouble joining a Zoom meeting using Puppeteer, my code is not capturing the password field. Can anyone assist? Here is my code snippet: const puppeteer = require("puppeteer-extra"); const StealthPlugin = require("puppeteer-extra-plu ...

Retrieving posted data in SailsJS

I attempted to retrieve the post data in my controller methods using the code snippet below: req.body.name Unfortunately, this approach did not yield the desired results. ...

Encountering issues when setting fitbounds beyond the scope of a jquery.each()

I am currently working on a Google Map project using JavaScript(v3). My goal is to display markers from XML data by utilizing jQuery. Below are the object and function that I have created to streamline this process: var VX = { map:null, bounds ...

How can I determine whether a value is present in a data attribute using jQuery?

I'm working with a HTML div that looks like this: <div id="myDiv" data-numbers="1 4 5 3 9 88 57 "></div> Within the data-numbers attribute of the div, there are random numbers separated by white space. My goal is to determine whether ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

The Recharts Line chart fails to display newly added data points when data is updated

My app features a straightforward tool that enables users to monitor their weight changes over time. Despite successfully receiving new data in the props, the chart does not update and display the new point. Recharts Component: import React from 'rea ...

Is there a way to deactivate middleware in Node, Express, and Mocha?

My application features a hello world app structured as follows: let clientAuthMiddleware = () => (req, res, next) => { if (!req.client.authorized) { return res.status(401).send('Invalid client certificate authentication.'); } ret ...

"Unsettled" JavaScript variable persists during Ajax page transition

I'm currently working on a CRUD app using php/js, where an ajax page change is essential. Within the "add view," there is a basic table and a button that adds a new row whenever you click on it. Initially, on the first load, clicking the button adds ...

The dynamic value feature in Material UI React's MenuItem is currently experiencing functionality issues

Whenever I use Select in Material UI for React, I encounter an issue where I always receive undefined when selecting from the drop-down menu. This problem seems to occur specifically when utilizing dynamic values with the MenuItem component. If I switch to ...

Is it possible to utilize JSX when developing an App using React CDN or the CRA (create-react-app) boilerplate template?

The HTML Code: <div id="app"></div> <script src="https://unpkg.com/react@latest/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@latest/umd/react-dom.develo ...

Setting up the Angular 2 router to function from the /src subfolder

My goal is to create two separate subfolders within my project: src and dist. Here are the key elements of my application: root folder: C:\Server\htdocs\ app folder: C:\Server\htdocs\src index.html contains <base href="/ ...

What is the method for an (angular) custom element to determine if a <slot> tag has been utilized?

I'm working with a custom element that has multiple named slots. Based on a certain state, one of the slots will be displayed. Here is an example of how the custom elements are structured: <slot></slot> <slot name="small"></slot& ...

Looking for the MIME file type requirement for Excel or spreadsheets?

Values in the 2nd column indicate the file MIME type. https://i.sstatic.net/qPcQD.png I am looking to create a condition that will be true for all of the above file MIME types. Specifically, I need a condition for all Excel files. This is what I attempte ...

timings and pauses utilizing JavaScript

Currently, I am facing a challenge while working on a Simon Says game. My struggle lies in the part where I need to illuminate the buttons that the user has to click. I am using a "for" loop to iterate through each element in the array where I have stored ...

Ensuring the existence of a MySQL database prior to executing a Node.js application

I am currently working on a Node.js/Express application that communicates with a MySQL server using Sequelize. I want to make sure that a particular database is created before the app starts running when using npm start. I think I need to create a one-ti ...

There appears to be an issue with the functionality of the JavaScript calculation function

Check out this JS Fiddle. I've tried my best in writing the script, but it just doesn't seem to work properly. If you could spare some time to review it and provide feedback on what I might be missing or doing wrong, I would greatly appreciate it ...

Utilizing JavaScript for selecting a radio button on click event

I have implemented a feature with four radio buttons to select a country. Upon clicking on any of the radio buttons, I utilize Ajax to retrieve the states corresponding to that specific country. To indicate to the end user that data processing is ongoing, ...

Developing a system for monitoring email open rates and geographical analytics using JavaScript?

I'm embarking on a project to develop an email tracker that can create a distinct pixel and monitor open rates using JavaScript with MeteorJS. Are there any valuable resources out there that could help me achieve this goal? I've come across exam ...

Refreshing an HTML table using instance variables from a C# class (utilizing jQuery and AJAX)

Explore <script type="text/javascript"> $(document).ready(function () { $("#viewDetails").click(function () { $.ajax( { type: "POST", url: '@Url.Action("GetDetail", "ControllerName")' ...