Pass a Value to a WebView

You must Login before you can answer or comment on any questions.

Hi, everyone. I'm sure this is a simple example, but I've only spent a day learning Titanium; so I have much to learn. :)

I want to load a webView, and pass an html fragment to it. Something like this:

var webview = Titanium.UI.createWebView({
    url : '../page.html'
});
webview.content = 'my static content';
 
var window = Titanium.UI.createWindow();
window.add(webview);
window.open({modal:true});
So this will correctly create the webView and load it into the new window. But, I can't seem to access that content variable from within page.html. I thought I could do Titanium.UI.currentWindow.content, but that doesn't work.

Any help? Thanks!

5 Answers

You can use the evalJS() function to execute Javascript code inside the webView.

var code = "document.getElementById('myDiv').innerText = 'custom html here';";
webView.evalJS(code);

— answered 3 years ago by Jacob Williams
answer permalink
1 Comment
  • Worked flawlessly! Bingo! Thanks a mill.

    I wrote the function name in... This example was for a results page after a form. It made my back button close the results page, and clear the form. The clear form function was within the html page head:

    backbutton.addEventListener('click', function() { winResults.close(); var code = "clearForms();"; webviewer.evalJS(code); });

    — commented 3 years ago by Glen McPherson

The usual method advised in the past is to utilize:

https://developer.appcelerator.com/apidoc/mobile/1.1/Titanium.App.Properties

  • MorningZ

Right, and I guess I could use that, but I was hoping for a more direct solution. I was under the impression that, as I long as I add properties directly to the webview, they'll be available to me from within it.

Using custom properties like you're trying to do should work, but try adding it to window instead of webview, so like this:

window.content = 'my static content';
Then you should be able to read it from your new window via Ti.UI.currentWindow.content

custom_properties.js and custom_properties_2.js examples in Kitchen Sink shows examples of how to use custom properties to pass data between windows.

These don't seem to be working for me. All I want is to create a webview, with a url of 'somepage.html', and from within it, have access to a variable from the JavaScript file that created it. I can obviously run JavaScript from within that html page, but I don't seem to have access to any of the variables from the window.

Your Answer

Think you can help? Login to answer this question!