Reading a Javascript object from UIWebview - javascript
I have a webpage which has data within a javascript object in it. I would like to get access to this data from the UIWebView to use within the native ObjectiveC code.
I have tried a number of ways
In the delegate method -(void) webViewDidFinishLoad:(UIWebView *) webView
I tried accessing the object using
[myWebView stringByEvaluatingJavaScriptFromString:#""];
but there didnt seem an easy way to pull in the structured data
Other option I thought was to
just load the HTML as a string and parse it but this seemed like a really ugly approach.
An example of the HTML I have is.
<html>
<head>
<script type="text/javascript">
$(function() {
myData[0] = {
name: 'data title',
data: [
[1281880800000, 4],[1282485600000, 12],[1283090400000, 15],[1283695200000, 107],[1284300000000, 11],[1284904800000, 14],[1285509600000, 3],[1286110800000, 10],[1286715600000, 12],[1287320400000, 2],[1287925200000, 304],[1288530000000, 18],[1289134800000, 22],[1289739600000, 5],[1290344400000, 6],[1290949200000, 14],[1291554000000, 6],[1292158800000, 10],[1292763600000, 9],[1293368400000, 0],[1293973200000, 4],[1294578000000, 2],[1295182800000, 17],[1295787600000, 6],[1296392400000, 4],[1296997200000, 7],[1297602000000, 50],[1298206800000, 2],[1298811600000, 3],[1299416400000, 3],[1300021200000, 301],[1300626000000, 1],[1301230800000, 72],[1301839200000, 6],[1302444000000, 5],[1303048800000, 2],[1303653600000, 5],[1304258400000, 7],[1304863200000, 8],[1305468000000, 34],[1306072800000, 12],[1306677600000, 6],[1307282400000, 2],[1307887200000, 2],[1308492000000, 7],[1309096800000, 30],[1309701600000, 63],[1310306400000, 3],[1310911200000, 9],[1311516000000, 3],[1312120800000, 4] ],
color: '#ff1430'
};
myData[1] = {
name: 'Other Data',
data: [
[1281880800000, 29],[1282485600000, 402],[1283090400000, 0],[1283695200000, 1],[1284300000000, 1],[1284904800000, 0],[1285509600000, 0],[1286110800000, 0],[1286715600000, 1],[1287320400000, 10],[1287925200000, 2],[1288530000000, 0],[1289134800000, 10],[1289739600000, 1],[1290344400000, 3],[1290949200000, 26],[1291554000000, 2],[1292158800000, 5],[1292763600000, 3],[1293368400000, 1],[1293973200000, 3],[1294578000000, 26],[1295182800000, 2],[1295787600000, 0],[1296392400000, 5],[1296997200000, 47],[1297602000000, 36],[1298206800000, 12],[1298811600000, 21],[1299416400000, 0],[1300021200000, 0],[1300626000000, 16],[1301230800000, 0],[1301839200000, 3],[1302444000000, 4],[1303048800000, 2],[1303653600000, 0],[1304258400000, 1],[1304863200000, 5],[1305468000000, 2],[1306072800000, 1],[1306677600000, 4],[1307282400000, 1],[1307887200000, 1],[1308492000000, 51],[1309096800000, 77],[1309701600000, 3],[1310306400000, 2],[1310911200000, 1],[1311516000000, 10],[1312120800000, 4] ],
color: '#007396'
};
</script>
</head>
<body>
</body>
</html>
EDIT:
To clarify I would like to be able to get access to the myData structure in the above HTML example within objective C as a NSDictionary or similar.
NSInteger x = [[[[[myDataArray objectAtIndex:0] objectForKey:#"data"] objectAtIndex:0] objectAtIndex:0]
I have used http://stig.github.com/json-framework for converting JSON into NSDictionary but was wondering how I could combine this to access this javascript object from within the HTML
I think this is a duplicate post. But still let me clarify your doubt -
[webView stringByEvaluatingJavaScriptFromString:#"obj.func();"];
EDIT: Check this - How to inject Javascript in UIWebView
Hope this helps...
Related
Trying to build HTML elements by code, functions included
This is my first post, hoping someone can help me: I wish to build a web project, where all the HTML elements are stored in database and taken from it to build the web page. i found a problem with the buttons, i cannot find a way to store the function for a button, i´m using Jquery to build the elements, for now the test element definitions are simulated in some arrays i left at the start of my Js file, the only way i can make the buttons to work is if the functions are hardcoded in the Js file, is there a way for me to bring the functions from database too? and having them in an array? this is my project sample: HTML <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <!--script src="functions.js"></script--> <script src="system.js"></script> <!--script src="elements.js"></script--> </head> <body> <body onload="addElements()"> <div id="div1"></div> </body> </html> JS File /** VARIABLE DEFINITIONS THESE ARE SUPPOSED TO COME FROM A DATABASE STILL UNKNOWN HOW TO BRING THE FUNCTIONS, AS STRING THEY ARE NOT ALLOWED. FOR NOW THERE ARE TEST FUNCTIONS. **/ let buttonIds = ['btn1', 'btn2']; let buttonText = ['Show Text', 'Show HTML']; let buttonFunc = [alert1, alert2]; //let buttonFunc = ['alert("Hi");', 'alert("Hello");']; let paragraphs = ['This is some <b>bold</b> text in a paragraph.', 'another <b>bold</b> test']; //HELPER FUNCTIONS // **** THESE ARE SUPPOSED TO COME FROM DATABASE, UNKNOWN HOW TO DO IT. **** function alert1() { alert("Hi"); } function alert2(){ alert("Hello"); } function addElements(){ for(var p=0; p<paragraphs.length; p++){ addParagraphs('#div1', paragraphs[p]); } for(var i=0; i<buttonIds.length; i++) { createButton( '#div1', buttonIds[i] , buttonText[i]); } } // ANY ELEMENTS FUNCTION IS DEFINED HERE ONCE THE PAGE IS LOADED. $(document).ready(function(){ for(var x=0;x<buttonIds.length; x++){ activateButton(buttonIds[x], buttonFunc[x]); } }); //HELPER FUNCTIONS USED TO BUILD THE HTML ELEMENTS ON THE MAIN PAGE. function addParagraphs(location, text){ $(location).append('<p id="test">'+text+'</p>'); } function createButton(location, id, text){ var definition; definition = "<button id="+id+">"+text+"</button>"; $(location).append(definition); } function activateButton(buttonId, functionName){ var composedId = "#"+buttonId; $(composedId).click(functionName); }
You can generate Javascript file serverside with all the funcions you need. Supposing Node.js you can do something like this: expressApp.get("some.js", (req, res) => { getDataFromDatabase() // depends on your database .then(data => { let body = 'function your_fn () { alert("'+ JSON.stringify(data) +'")}'; res.send(body); }) });
One approach is use an object to store the functions in javascript and use property names stored in db to associate which function to use for which element. Without knowing more about your use case it is hard to really help design a proper system to use Following is a very basic example // functions stored in js file const funcs = { f1: function(e){ console.log('func one called , id = ', this.id)}, f2: function(e){ console.log('func 2 called , id = ', this.id)} } // data from database const elems = [ {id: 1, className: 'one', func:'f1', text:'Item 1'}, {id: 1, className: 'two', func:'f2', text:'Item 2'} ] elems.forEach(e => { const $el= $('<div>', {id: e.id, class: e.className, text:e.text, click: funcs[e.func]}) $('body').append($el); }); div {margin:1em;} .one {color:red;} .two {color:green;} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <strong>Click on items</strong><br><br>
Accessing java variable from javascript in spring mvc
i am relatively new to spring mvc.what i am trying to do is pass a variable as model attribute and try and access it on page load with javascript on my JSP page. my java code is as follows model.addAttribute("leagueCode",leagueCode); model.addAttribute("league","new"); return "redirect:/Dashboard"; and on jsp side i am trying to access it by following <script type="text/javascript"> function myFunction() { var leagueCode=${leagueCode}; alert(leagueCode); } </script> </head> <body onload="myFunction()"> but i am getting the value as blank. is this the right way i am following or is there any other way this has to be done? please help
In the JSP page you can set the values as javascript variables by adding a script tag in the <head> with the assignment inside as a json object for example: <script> var myServerSideVars = { "aServerSideVarName" : "<here you set the value with el/jslt/scriptlet>", "anotherServerSideVarName" : "<here you set the value with el/jslt/scriptlet>" }; </script> EDIT I Example using EL (Expression Language) but the same could be done with scriptlets if you are using that (<% %>): Lets say in your Servlet you put a Car instance in the request before forwarding to the JSP page. The car: public class Car{ protected String brand; protected String year; //getters and setters for the two properties. } In the Servlet you put it into the request: Car car = new Car(); car.setBrand("BMW"); car.setYear("2017"); request.setAttribute("carInRequest", car); In the JSP you set it to a Json Object accessible from javascript. Before closing the body tag I put a simple example of how the var can be accessed from javascript. I haven't run it so it may have some typo or error to correct: <%#taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <html> <head><title>System.out.println</title> <script> var aCar= { "brand" : "${requestScope.carInRequest.brand}", "year" : "${requestScope.carInRequest.year}" }; </script> </head> <body> <h2>Brand: <span id="brandPlaceHolder"></span></h2> <h2>Year: <span id="yearPlaceHolder"></span></h2> </body> <script> var brandSpan = document.findElementById("brandPlaceHolder"); brandSpan.html = aCar.brand; var yearSpan = document.findElementById("yearPlaceHolder"); brandSpan.html = aCar.year; </script> </html>
how to pass a json object from a php page to a js variable
First off, my apologies if this is already addressed in another post - I'm sure it is, but I have not been able to figure it out. Second, I have a PHP page that outputs an array in a JSON format like this: [{ "chemical":"Corrosion_Inhibitor", "TargetDose":81, "AppliedDose":26, "ppbbl":"$0.97" }, { "chemical":"Scale_Inhibitor", "TargetDose":56, "AppliedDose":63, "ppbbl":"$1.00" }, { "chemical":"Biocide", "TargetDose":55, "AppliedDose":55, "ppbbl":"$0.30" }, { "chemical":"Friction_Reducer", "TargetDose":23, "AppliedDose":44, "ppbbl":"$0.42" }] I would like to pass that array to a variable tableData in JavaScript so that I can populate a table on another PHP page. Any guidance would be greatly appreciated. Clearly I am not an expert in either of these languages.
Sounds like you want to dynamically generate a table from a JSON response? If you are sending a request to the php script that outputs that JSON response, you can use JSON.parse(responseData) to parse the JSON string response to a JS variable array/array of objects.
This is a basic way to do that: <?php $dataFromPHP = '[{ "chemical":"Corrosion_Inhibitor", "TargetDose":81, "AppliedDose":26, "ppbbl":"$0.97" }, { "chemical":"Scale_Inhibitor", "TargetDose":56, "AppliedDose":63, "ppbbl":"$1.00" }, { "chemical":"Biocide", "TargetDose":55, "AppliedDose":55, "ppbbl":"$0.30" }, { "chemical":"Friction_Reducer", "TargetDose":23, "AppliedDose":44, "ppbbl":"$0.42" }] '; ?> <html> <body> <!-- main HTML content --> </body> <script> var tableData = <?php echo $dataFromPHP ?>; // do whatever you want with that data </script> </html>
Parse content from a html page
Need to dynamically update contents in a div of main page, based on data fetched from other html page setInterval( function() { $.ajax({ type:'GET', url:"url for status", success : function(data){ console.log(data); } }) },3000); The content of 'data' printed in developer tool console is: <html> <style> </style> <head> </head> <script> var conns=[{num:1, id:1, Conn:[{type:'ppp', Enable:1, ConnectionStatus:'Disconnected', Name:'CONNECTION_1', Uptime:0, ConnectionError:'TIME_OUT', .............. }] }, {num:2, id:2, Conn:[{type:'ppp', Enable:1, ConnectionStatus:'Disconnected', Name:'CONNECTION_2', Uptime:0, ConnectionError:'TIME_OUT', .............. }] }] </script> </html> Need to extract the ConnectionStatus, Name and ConnectionError from this content and display it in respective div in main page.
I would recommend using a different transfer type, however, you could use something like this: function break_out_each_id(){//returns array of indexes where id starts var i = 0; id_objs = []; while data.indexOf('id', i) > -1{ id_objs[i] = data.indexOf('id', i); i++; } return id_objs } function find_values(){//pseudo code use the array of indexes from first index to next index in that string, do index of each value you are looking for (ConnectionStatus...) then parse that line after the ':' to get the value. Do this for each index in indexes array } Sorry for the pseudo code, but this post is getting really long. Like I said, it would be MUCH better to just send the response as JSON (even if it is a stringified version of it). In that case you could just do a simple JSON.parse() and you'd be done.
Backbone: getting the html code of a view?
In order to write the HTML code of social icons (Twitter, Linkedin, etc) to a textarea so that the user can use that code elsewhere, I would like to get the HTML code of the view element, but I'm having some issues. To help illustrate this better, here is the code that creates the view: define(function(require, exports, module) { var _ = require('underscore'); var GridControlView = require('pb/views/grid-control'); var SocialiconsControlDialog = require('pb/views/socialicons-control-dialog'); var template = require('text!pb/templates/socialicons-grid-control.html'); var SocialiconsGridControlView = GridControlView.extend({ template: _.template(template) ,templateVars: { partials: { facebook: require('text!pb/templates/socialicons-grid-control-facebook.html') ,twitter: require('text!pb/templates/socialicons-grid-control-twitter.html') ,googleplus: require('text!pb/templates/socialicons-grid-control-googleplus.html') ,pinterest: require('text!pb/templates/socialicons-grid-control-pinterest.html') ,linkedin: require('text!pb/templates/socialicons-grid-control-linkedin.html') } } ,control_dialog: SocialiconsControlDialog }); return SocialiconsGridControlView; }); And, for example, the Linkedin template looks like this: <script src="//platform.linkedin.com/in.js?<%- t.cache_buster %>" type="text/javascript">lang: en_US</script> <script type="IN/Share" data-counter="<%- t.linkedin_option_countmode %>"></script> What I would like to retrieve, is the parsed template code as text, something such as: <script type="text/javascript" src="//platform.linkedin.com/in.js?0.4670609195438331"> <script data-counter="top" type="IN/Share+init"> But using something such as: control_view.render().$el.innerHTML;, control_view.render().$el.html().text() or control_view.render().$el.html().replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, ""); doesn't return text; it returns the full HTML, and produces a Linkedin icon (when I just want the text to be written to a textarea). Any thoughts? Update ** I noticed that the code control_view.render().$el is working correctly on other places of the application, and returning HTML code, but for some reason in this view where I'm trying it doesn't. The code seems to break at: $control = control_view.render().el; and in the console I get an error which is: TypeError: t is undefined - underscore-min.js (line 3)
Use the .outerHTML property of the $el. var html = $('<script type="text/javascript" src="//platform.linkedin.com/in.js?0.4670609195438331">' + '<script data-counter="top" type="IN/Share+init">'); var text = html[0].outerHTML; $('textarea').val(text); jsFiddle