JavaScript injection into Java WebView - javascript

Good evening,
I'm trying to get the following JavaScript snippet to run inside an WebView of an Android app. Trust me, I've studied several pages in here and I did it similarly.
That's the snippet:
function myFunction() {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var newNode = document.createElement("span");
newNode.setAttribute("style", "background-color: #FFF000;");
range.surroundContents(newNode);
}
I'm working on a Browser app and I want to be able to highlight text passages. For that I've made a custom text selection menu, which contains an onClickListener.
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.loadUrl(
"javascript:(function() { " +
"var element = document.getElementById('hplogo');"
+ "element.parentNode.removeChild(element);" +
"})()");
}});
That example works perfectly and I wanted to adapt it to my JavaScript snippet. My Code is the following:
webView.loadUrl("javascript:(function() { " +
"var selection = window.getSelection();" +
"var range = selection.getRangeAt(0);" +
"var newNode = document.createElement('span');"+
"sel.addRange(range);"+
"newNode.setAttribute('style', 'background-color: #FFF000;');"+
"range.surroundContents(newNode);"+
"})()");
That drives me completely insane.
Thanks in advance.

Is the issue that your javascript code has "sel.addRange" instead of "selection.addRange"

Related

Using CEFSharp to edit <textarea>

I am able to edit a regular textbox within an iFrame in CefSharp like so:
Browser1.GetBrowser().GetFrame("iFrame1").ExecuteJavaScriptAsync("document.getElementById('ElementID').value=" + '\'' + "1234" + '\'');
However, because a textarea doesn't have a value:
<iframe id="iFrame1" name="iFrame1">
<textarea name="txtareaname" id="txtareaname1">sometexthere</textarea>
</iframe>
I am unable to execute a similar line of code to edit the text in the textarea:
textarea.Browser1.GetBrowser().GetFrame("iFrame1").ExecuteJavaScriptAsync("document.getElementById('txtareaname1').value=" + '\'' + "1234" + '\'');
I have also tried:
textarea.Browser1.GetBrowser().GetFrame("iFrame1").ExecuteJavaScriptAsync("document.getElementById('txtareaname1').innertext=" + '\'' + "1234" + '\'');
How do I adjust my code to edit this textarea?
OP: However, because a textarea doesn't have a value I am unable to
execute a similar line of code to edit the text in the textarea.
The assumption is wrong, setting value attribute works fine for teaxtarea.
You should just make sure the document, including the iframe has been loaded and you have selected the correct iframe using correct name and then you have selected the correct textarea using correct id.
Example
Here is a minimal complete verifiable example which shows how you can find the iframe and set the value of a textarea inside the iframe.
To make the example independent from externals sources and make verification easier, instead of initializing iframe using its src attribute, I've initialized iframe using script.
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
var content = new HtmlString(#"
<!DOCTYPE html>
<html>
<body>
<iframe id=""iFrame1"" name=""iFrame1"" src=""about:blank""></iframe>
<script>
var doc = document.getElementById('iFrame1').contentWindow.document;
doc.open();
doc.write('<html><head><title></title></head><body>' +
'Address:<br>' +
'<textarea id=""myTextarea"">342 Alvin RoadDucksburg</textarea>' +
'</body></html>');
doc.close();
</script>
</body>
</html>
");
var browser = new ChromiumWebBrowser(content)
{ Dock = DockStyle.None, Size = new Size(400, 200), Location = new Point(8, 42) };
Controls.Add(browser);
var button = new Button() { Text = "Click Me", Location = new Point(8, 8) };
Controls.Add(button);
button.Click += (obj, args) => {
browser.GetBrowser().GetFrame("iFrame1")
.ExecuteJavaScriptAsync("document.getElementById('myTextarea').value=" +
"'Fifth Avenue, New York City'");
};
}

How to insert a javascript file to my BHO Extension for IE-11? I want to insert a javascript file with multiple lines

I want to insert a javascript into a page whenever a site loads using Browser Helper object in IE-11.
public void OnDocumentComplete(object pDisp, ref object URL)
{
HTMLDocument document = (HTMLDocument)webBrowser.Document;
IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)
document.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject =
(IHTMLScriptElement)document.createElement("script");
scriptObject.type = #"text/javascript";
scriptObject.text = "\nfunction hidediv(){document.getElementById" +
"('myOwnUniqueId12345').style.visibility = 'hidden';}\n\n";
((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);
string div = "<div id=\"myOwnUniqueId12345\" style=\"position:" +
"fixed;bottom:0px;right:0px;z-index:9999;width=300px;" +
"height=150px;\"> <div style=\"position:relative;" +
"float:right;font-size:9px;\"><a " +
"href=\"javascript:hidediv();\">close</a></div>" +
"My content goes here ...</div>";
document.body.insertAdjacentHTML("afterBegin", div);
}
I want to get a javascript file inserted into page instead of using scriptObject.text.

WKWebView and InnerText with newline

I am currently working on implementing a web view inside of my iOS application using Xamarin. My webView is a WkWebView. My issue is that any time the text I am passing in has a new line it fails to display. However, testing my function in my browser (chrome) along with Safari I see that it executes just fine. I did some searching and I also tried to replace the \n character with \r\n, but that did not solve my issue. What am I missing?
C#:
private void BuildText(FormEntries entry, FormResponseAnswers formAnswers) {
string function = "buildText('" + entry.Text + "', '" + formAnswers.Answer + "');";
var javaScriptCmd = (NSString)function;
webView.EvaluateJavaScript(javaScriptCmd, null);
}
formAnswers.Answer that is causing the issue is:
"Hello world from the device, I do not know how well this will display our data at all. But we will see how this works. I wonder, if I were to add enter keys will it work?\n\n\nI kinda doubt it. ";
JS:
function buildText(entryText, answer) {
var answerAreaDiv = document.getElementById('answerArea');
var holder = document.createElement('div');
holder.classList.add('holder');
var entryLabel = document.createElement("label");
entryLabel.textContent = entryText + ':';
var answerLabel = document.createElement("label");
answerLabel.innerText = answer;
holder.appendChild(entryLabel);
holder.appendChild(answerLabel);
answerAreaDiv.appendChild(holder);
}
HTML:
<body>
<div id="answerArea">
</div>
</body>
HTML elements don't line break unless you explicitly ask them to; line breaks such as \n are treated as spaces. Try inserting HTML instead, so that you can replace your newline with a <br>:
answerLabel.innerHTML = answer.replace(/\n/g, '<br>');
Example:
document.body.appendChild(document.createElement('label')).innerHTML = `first line
second line`.replace(/\n/g, '<br>');

c# - autofill program, how can i autofill select tag in browser? select box?

I recently want to make auto-typing, auto-fill Explorer browser, using Windows program with c#.net programming.
I can auto type in text type but I cannot autotype the 'select tag'.
I searched and I think I can use 'setAttribute("value","selectIndexnumber")'
but, I didn't work well. Explorer does not perceive the 'change' state.
So first, I used IHTMLElement3.FireEvent("onchange",null); to invoke 'onchange'
but it didn't work, too.
and Secondely, I used SendKeys.Send("{TAB}");
but it didn't work, too.
how can I autofill the 'select tag' well with no problem like user change the select tag?
please help me. thanks in advance!
below is the code that i wrote.
private void button3_Click(object sender, EventArgs e)
{
SHDocVw.InternetExplorer browser;
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
string filename;
MessageBox.Show("shellWindows number is " + shellWindows.Count);
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
filename = System.IO.Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if ((filename == "iexplore"))
{
browser = ie;
String myDocURL = browser.Document.url;
MessageBox.Show("this is url" + myDocURL);
if (myDocURL == "https://hankooktire.recruiter.co.kr/app/applicant/modifyResume")
{
IHTMLDocument3 ihtml3doc = (IHTMLDocument3)browser.Document;
IHTMLElement3 ihtml3ele = ihtml3doc.getElementById("jobnoticeSn") as IHTMLElement3;
IHTMLElement ihtmlele = ihtml3doc.getElementById("jobnoticeSn");
ihtmlele.setAttribute("value", "4");
IHTMLSelectElement selEle = ihtml3ele as IHTMLSelectElement;
//selEle.selectedIndex=4;
SendKeys.Send("{TAB}");
ihtml3ele.FireEvent("onchange", null);
//SendKeys.Send("{TAB}");
ihtml3doc.getElementById("jobnoticeSn").children(4).setAttribute("selected", "true");
SendKeys.Send("{TAB}");
//ihtml3doc.getElementById("jobnoticeSn").children(4).setAttribute("checked", "true");
//ihtml3doc.getElementById("jobnoticeSn").children(4).setAttribute("selectedIndex", "true");
//ihtml3doc.getElementById("jobnoticeSn").setAttribute("selected", "selected");
//ihtml3doc.getElementById("jobnoticeSn").setAttribute("value", "8130");
ihtml3doc.getElementById("name").setAttribute("value", "김준혁");
ihtml3doc.getElementById("birthday").setAttribute("value", "1989-11-18");
ihtml3doc.getElementById("man").setAttribute("checked", "true");
ihtml3doc.getElementById("email").setAttribute("value", "jjunest#gmail.com");
ihtml3doc.getElementById("password").setAttribute("value", "emfla248248");
//ihtml3doc.getElementById("password").scrollIntoView();
}
}
}
}

amcharts not showing theme background in Android webview

I am using a webview to host amcharts in an android application. The basic setup for the code is that I form an HTML document programatically and load it hosted in my assets folder. The amcharts libraries are located in a subdirectory of the assets folder. So far, this setup has allowed me to generate charts in a webview with locally provided data. In order to change the chart's theme, I have been following a tutorial from the amcharts websight http://www.amcharts.com/tutorials/working-with-themes/. The tutorial allowed me to change the way the bars in the chart look, but the background remains unchanged. I have also looked at some posts reporting that the themes of other users were not working. My problem differs in the sense that the way the graph is being drawn is correct according to the theme. It is only the background that is not being set.
This is the class I use to build the test chart data.
public class AmChartsUtils {
public static String getTestHtml(String chartData) {
chartData = chartData.replace("\n", "");
return "<HTML><HEAD>" + getHeadContent(chartData)+ "<BODY>"+ getBodyContent() + "</BODY></HTML>";
}
private static String getHeadContent(String chartData) {
return "<script src=\"js/amcharts.js\" type=\"text/javascript\"></script>"+
"<script src=\"js/serial.js\" type=\"text/javascript\"></script>" +
"<script src=\"js/themes/dark.js\" type=\"text/javascript\"></script>" +
"<script src=\"js/themes/chalk.js\" type=\"text/javascript\"></script>" +
// "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\">"
getChartData(chartData);
}
private static String getChartData(String chartData) {
StringBuilder sb = new StringBuilder();
sb.append("<script type=\"text/javascript\">");
sb.append("var chartData = [");
sb.append(chartData);
sb.append("];");
sb.append(buildStartCommand());
sb.append("</script>");
return sb.toString();
}
private static String buildStartCommand() {
StringBuilder sb = new StringBuilder();
sb.append("if(document.body){");
sb.append("document.body.style.backgroundColor = \"#282828\";");
// sb.append("document.body.style.backgroundImage = \"url(\" + bgImage + \")\";");
sb.append("}");
sb.append("AmCharts.ready(function() {");
sb.append("var chart = new AmCharts.AmSerialChart(AmCharts.themes.chalk);");
sb.append("chart.dataProvider = chartData;");
sb.append("chart.categoryField = \"country\";");
sb.append("chart.angle = 30;");
sb.append("chart.depth3D = 15;");
sb.append("chart.backgroundColor = \"#282828\";");
sb.append("chart.backgroundAloha = \"1.0\";");
sb.append("var graph = new AmCharts.AmGraph();");
sb.append("graph.valueField = \"visits\";");
sb.append("graph.type = \"column\";");
sb.append("chart.addGraph(graph);");
sb.append("chart.write('chartdiv');");
sb.append("});");
return sb.toString();
}
private static String getBodyContent() {
return "<div id=\"chartdiv\" style=\"width: 400px; height: 400px;\"></div>";
}
}
Here is how the chart apears on the screen.
The expected result is the same graph with a dark chalkboard background.
Does anyone know why the background is not coming in? Thanks in advance for any help recieved.
There is a typo in your code:
sb.append("chart.backgroundAloha = \"1.0\";");
It should read this instead:
sb.append("chart.backgroundAlpha = \"1.0\";");
Also, alpha is a numeric parameter. I strongly suggest you supply it as number.
I know you won't be displaying it in some old browsers that might be thrown off by this, but it's a good idea to keep your JavaScript apps as strongly typed as possible.

Categories