How to manipulate webpage by weBrowser control after JS is executed? - javascript

I have webpage which gets data by json and then generates html from that data. I want to be able to do element.invokeMember("click"); (webBrowser winForms control) on source generated by JS. How to do that in c#?
I can see the source in firebug only.
What have I already done: ( _ie from here: How to make WebBrowser wait till it loads fully?)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.ProgressChanged += new WebBrowserProgressChangedEventHandler(_ie);
}
private void _ie(object sender, WebBrowserProgressChangedEventArgs e)
{
int max = (int)Math.Max(e.MaximumProgress, e.CurrentProgress);
int min = (int)Math.Min(e.MaximumProgress, e.CurrentProgress);
if (min.Equals(max))
{
Console.Write("complete");
var menus = webBrowser1.Document.GetElementsByTagName("menu");
Console.Write(menus.Count);
var votes = new List<HtmlElement>();
foreach (HtmlElement menu in menus)
{
Console.Write("found");
var ass = menu.GetElementsByTagName("a");
foreach (HtmlElement a in ass)
{
if (a.GetAttribute("class").Contains("vote-up"))
{
a.InvokeMember("click");
}
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("xxxxx");
}
}
HTML:
http://pastebin.com/0KGCwtqs
copied from firebug, so some tags are collapsed. I want only <menu>-><footer>-> <a class="vote-up ...">
Console.Write("found") is not executed. So webBrowser can not even find <menu>
solved
Just use tricky JS
var elements=document.getElementsByClassName('vote-up');for (index = 0; index < elements.length; index++) {elements[index].click();}

solved
Just use some js and invoke it from browser
var elements=document.getElementsByClassName('vote-up');
for (index = 0; index < elements.length; index++) {elements[index].click();}

Related

Edit->Find for WebView2 UI Component (WPF/C#/javascript)

I need to implement "Edit->Find" function for a WebView2 UI Component using WPF/C#/javascript... Below you will find two examples: One that is made for a TextBox UI Control called MainWindow1, and the other that is implemented for a WebView2 UI Control that is called MainWindows2. I'm giving both examples because I need to work the same way for each one. The TextBox example is working, but the WebView2 example is missing some javascript code to finish it and maybe requires some tweeting of the C# calls to WebView2.
First, I implemented a "Find Forward" button for a TextBox that I can click multiple times to find the next string matching the search pattern in the textbox. And Here's my XML and C# for it:
MainWindow1 GUI:
MainWindow1 XML:
<Window x:Class="WpfApp1.MainWindow1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Loaded="Window_Loaded"
Title="MainWindow1" Height="450" Width="800">
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top" Background="Aqua">
<TextBox Name="TboxFind" Width="80" Text="id"/>
<Button Name="FindForward" Content="FindForward"
Click="FindForward_Click"/>
</StackPanel>
<TextBox Name="textbox1" VerticalScrollBarVisibility="Auto"/>
</DockPanel>
</Window>
MainWindow1 C#:
using System.Text.RegularExpressions;
using System.Windows; using System.Windows.Controls;
namespace WpfApp1 {
public partial class MainWindow1 : Window {
public MainWindow1() {InitializeComponent();}
private void Window_Loaded(object sender, RoutedEventArgs e) {
string text1 = "";
for (int i = 0; i < 10000; i++) {
text1 = text1 + "id" + i.ToString() + "\n";}
textbox1.Text = text1;textbox1.Focus();textbox1.CaretIndex = 0;
}
private void TextBoxGotoLine(TextBox textbox1, int linenum) {
var target_cpos
= textbox1.GetCharacterIndexFromLineIndex(linenum);
var target_char_rect
= textbox1.GetRectFromCharacterIndex(target_cpos);
var first_char_rect = textbox1.GetRectFromCharacterIndex(0);
textbox1.ScrollToVerticalOffset(target_char_rect.Top
- first_char_rect.Top);
}
private void FindForward_Click(object sender, RoutedEventArgs e) {
string pattern = #"(?i)(" + Regex.Escape(TboxFind.Text) + #")";
string text1 = textbox1.Text.Substring(
textbox1.CaretIndex + textbox1.SelectionLength);
var match1 = Regex.Match(text1, pattern);
if (match1.Success) {
textbox1.Focus();
textbox1.Select(textbox1.CaretIndex
+ textbox1.SelectionLength
+ match1.Index, match1.Groups[0].Length);
} //if
} //function
}/*class*/ }/*namespace*/
The problem I'm having is that I also need this same feature for a WebView2 UI Control.
So I install the WebView2 UI Control:
WebView2 Install:
PM > Install-Package Microsoft.Web.WebView2
Add to XML: xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
using Microsoft.Web.WebView2.Core;
And here's my corresponding XML and C# demo code that should work the same as the first example I have given:
MainWindow2 GUI:
MainWindows2 XML:
<Window x:Class="WpfApp1.MainWindow2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wv2
="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Loaded="Window_Loaded"
Title="MainWindow2" Height="450" Width="800" >
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top" Background="Aqua">
<TextBox Name="SearchStr" Width="80" Text="id"/>
<Button Name="FindForward"
Content="FindForward" Click="FindForward_Click"/>
</StackPanel>
<wv2:WebView2 Name="webview2" CoreWebView2InitializationCompleted
="webview2_CoreWebView2InitializationCompleted" />
</DockPanel>
</Window>
MainWindow2 C#:
using System.Windows; using System.Threading;
using Microsoft.Web.WebView2.Core;
namespace WpfApp1 {
public partial class MainWindow2 : Window {
public MainWindow2() {InitializeComponent(); SearchStr.Focus(); }
private async void Window_Loaded(object sender, RoutedEventArgs e) {
await webview2.EnsureCoreWebView2Async();
}
private void webview2_CoreWebView2InitializationCompleted(
object sender, CoreWebView2InitializationCompletedEventArgs e)
{
string html = "";
for (int i = 0; i < 100; i++) {
string id = "id" + i.ToString();
html = html + "<b>" + id + "</b><br/>";
}
webview2.CoreWebView2.NavigateToString(html);
}
private async Tasks.Task<string> Find(string pattern) {
string js = "";
js = js + "var m1 = document.getElementById(""body"")";
js = js + "/*... ??? what goes here ??? */";
// Find and highlight one at a time, and scroll into view ...
// repeat find from beginning of html body when done ...
// See MainWindow1 example with TextBox for desired behavior here.
return await webview2.ExecuteScriptAsync(js);
}
private void async FindForward_Click(object s, RoutedEventArgs e) {
await Find(SearchStr.Text);
}
}/*class*/ }/*namespace*/
How to use WebBrowser UI Control to do a:
Menu->Edit->Find "SearchStr1"
When I click FindForward Button? I'm thinking it has something to do with executing Javascript on the DOM? each time the button is pressed?

How to properly reward player with Admob in Unity?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using UnityEngine.UI;
public class admobVideo : MonoBehaviour {
RewardBasedVideoAd rewardBasedVideo;
static InterstitialAd interstitial;
string VideoID = "ca-app-pub-6032262586397129~2821965113";
string adUnitId = "ca-app-pub-6032262586397129/5003220953";
public static admobVideo Instance;
void Start ()
{
Instance = this;
DontDestroyOnLoad(gameObject);
RequestRewardBasedVideo();
RequestInterstitial();
}
public void RequestRewardBasedVideo()
{
rewardBasedVideo = RewardBasedVideoAd.Instance;
rewardBasedVideo.LoadAd(new AdRequest.Builder().Build(), adUnitId);
}
public void RequestInterstitial()
{
interstitial = new InterstitialAd(VideoID);
interstitial.LoadAd(new AdRequest.Builder().Build());
}
public void ShowAd()
{
if(rewardBasedVideo.IsLoaded())
{
rewardBasedVideo.Show();
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
}
public static void ShowInter()
{
showInterstitial(interstitial);
}
private void showAdd(RewardBasedVideoAd r)
{
if (r.IsLoaded())
{
//Subscribe to Ad event
r.Show();
r.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
PlayerPrefs.SetInt("coins", PlayerPrefs.GetInt("coins") + 5);
GameObject.FindGameObjectWithTag("Coins").GetComponent<Text>().text = PlayerPrefs.GetInt("coins").ToString();
GameObject.FindGameObjectWithTag("Double").GetComponent<Button>().interactable = false;
Debug.Log("Pref: " + PlayerPrefs.GetInt("coins"));
}
static void showInterstitial(InterstitialAd i)
{
if (i.IsLoaded())
{
i.Show();
}
}
}
I am rewarding players with 5 coins , But when I click button nothing appears , I have tried to change code in many ways but no positive result.
when i click in the button in unity the console show me "Dummy is loaded" and "Dummy showrewardedbasedvideoad"
Method that is called upon button click is ShowAd(). Please Help
Please check by adding debug in HandleRewardBasedVideoRewarded method to check if it's called.
Also check you have added listener for that as you have not mentioned this in your code mentioned above.
rewardBasedVideo.OnAdRewarded += this.HandleRewardBasedVideoRewarded;
You have not initialised mobileAds with your app id:
MobileAds.Initialize();

CefSharp Inject Javascript prior to any document load/processing

For a project I am working on I need to inject javascript prior to any of the webpage document processing begins. This can easily be achieved via the WebBrowser component, but I am encountering difficulty using CefSharp.
Here is a simplification of the problem, a webpage needs an "InjectedObject" to be present to function. Calling the webpage without injection occurring at the very top of the document, or being evaluated/executed before the document is processed would result in:
=====html example output on failure=====
isObjectPresent?
false
=====
Where as I need the webpage to display:
=====html example output on success=====
isObjectPresent?
true
=====
<html>
<head>
<script>
isObjectPresent = typeof InjectedObject == "object";
</script>
</head>
<body>
<p>isObjectPresent?</p>
<div id="result"></div>
<script>
document.getElementById("result").innerHTML = isObjectPresent;
</script>
</body>
</html>
Looking at all the available suggestions would indicate I should use LoadingStateChanged() or FrameLoadEnd() to inject the script, ie:
public void OnFrameLoadEnd(object sender, FrameLoadEndEventArgs args) {
if (args.Frame.IsMain) {
args.Frame.ExecuteJavascriptAsync("window.InjectedObject = {};");
}
}
However all iterations I have tried of this, and even using FrameLoadStart, has resulted in the inserted javascript occurring after the document has begun processing. Is there any example of a true javascript injection insuring it occurs BEFORE document processing begins. (making sure to avoid a race condition/timing issue).
As an example of the WebBrowser component behavior that I am looking to imitate is:
private void uiWebBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
var browser = (WebBrowser)sender;
var document = browser.Document as HTMLDocument;
var head = document.getElementsByTagName("head").Cast<HTMLHeadElement>().First();
if (head != null)
{
var script = document.createElement("script") as IHTMLScriptElement;
script.text = "window.InjectedObject = {};"
if (head.firstChild != null)
{
head.insertBefore((IHTMLDOMNode)script, head.firstChild);
}
else
{
head.appendChild((IHTMLDOMNode)script;
}
}
}
Any help or suggestion is welcome, ideally I'd like to avoid downloading the page via an internet request parsing and inserting, and then using loadhtml, since I expect I would have to do that potentially for All navigation actions that impacted the main frame, which sounds like a hack job.
Following up from the comments it was suggested that the javascript V8 engine context was sufficient for the above use case. Attempting to implement the OnContextCreated method from the IRenderProcessMessageHandler interface has the same results.
==MainWindow.xaml==
<Window x:Class="ExampleCefSharp001.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:cefSharp="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ExampleCefSharp001"
mc:Ignorable="d"
Title="MainWindow" Height="1000" Width="1100">
<Grid>
<cefSharp:ChromiumWebBrowser x:Name="uiWebView"></cefSharp:ChromiumWebBrowser>
</Grid>
</Window>
==MainWindow.xaml.cs==
public partial class MainWindow : Window
{
JavascriptManager jsmanager;
public MainWindow()
{
InitializeComponent();
jsmanager = new JavascriptManager(uiWebView);
}
}
public class JavascriptManager : ILoadHandler, IRenderProcessMessageHandler
{
string injection = "window.InjectedObject = {};";
public JavascriptManager(ChromiumWebBrowser browser)
{
browser.LoadHandler = this;
browser.RenderProcessMessageHandler = this;
// Lets just pretend this is a real url with the example html above.
browser.Address = "https://www.example.com/timingtest.htm"
}
public void OnContextCreated(IWebBrowser browserControl, IBrowser browser, IFrame frame)
{
frame.ExecuteJavaScriptAsync(injection);
}
}
I do appreciate the comments and suggestions. If there is something I am missing please let me know!
Finally got back to this. Heavily based on example found in: CefSharp.Example/Filters/FindReplaceResponseFilter.cs
implementing the IRequestHandler and IResponseFilter interfaces:
==MainWindow.xaml==
<Window x:Class="ExampleCefSharp001.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:cefSharp="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ExampleCefSharp001"
mc:Ignorable="d"
Title="MainWindow" Height="1000" Width="1100">
<Grid>
<cefSharp:ChromiumWebBrowser x:Name="uiWebView"></cefSharp:ChromiumWebBrowser>
</Grid>
</Window>
==MainWindow.xaml.cs==
public partial class MainWindow : Window
{
JavascriptManager jsmanager;
public MainWindow()
{
InitializeComponent();
jsmanager = new JavascriptManager(uiWebView);
}
}
public class JavascriptManager : IRequestHandler
{
string injection = "window.InjectedObject = {};";
public JavascriptManager(ChromiumWebBrowser browser)
{
browser.RequestHandler = this;
// Lets just pretend this is a real url with the example html above.
browser.Address = "https://www.example.com/timingtest.htm"
}
public IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
if (frame.IsMain && request.ResourceType == ResourceType.MainFrame)
{
return new JavascriptInjectionFilter(injection);
}
return null;
}
}
public class JavascriptInjectionFilter : IResponseFilter
{
/// <summary>
/// Location to insert the javascript
/// </summary>
public enum Locations
{
/// <summary>
/// Insert Javascript at the top of the header element
/// </summary>
head,
/// <summary>
/// Insert Javascript at the top of the body element
/// </summary>
body
}
string injection;
string location;
int offset = 0;
List<byte> overflow = new List<byte>();
/// <summary>
/// Constructor
/// </summary>
/// <param name="injection"></param>
/// <param name="location"></param>
public JavascriptInjectionFilter(string injection, Locations location = Locations.head)
{
this.injection = "<script>" + injection + "</script>";
switch (location)
{
case Locations.head:
this.location = "<head>";
break;
case Locations.body:
this.location = "<body>";
break;
default:
this.location = "<head>";
break;
}
}
/// <summary>
/// Disposal
/// </summary>
public void Dispose()
{
//
}
/// <summary>
/// Filter Processing... handles the injection
/// </summary>
/// <param name="dataIn"></param>
/// <param name="dataInRead"></param>
/// <param name="dataOut"></param>
/// <param name="dataOutWritten"></param>
/// <returns></returns>
public FilterStatus Filter(Stream dataIn, out long dataInRead, Stream dataOut, out long dataOutWritten)
{
dataInRead = dataIn == null ? 0 : dataIn.Length;
dataOutWritten = 0;
if (overflow.Count > 0)
{
var buffersize = Math.Min(overflow.Count, (int)dataOut.Length);
dataOut.Write(overflow.ToArray(), 0, buffersize);
dataOutWritten += buffersize;
if (buffersize < overflow.Count)
{
overflow.RemoveRange(0, buffersize - 1);
}
else
{
overflow.Clear();
}
}
for (var i = 0; i < dataInRead; ++i)
{
var readbyte = (byte)dataIn.ReadByte();
var readchar = Convert.ToChar(readbyte);
var buffersize = dataOut.Length - dataOutWritten;
if (buffersize > 0)
{
dataOut.WriteByte(readbyte);
dataOutWritten++;
}
else
{
overflow.Add(readbyte);
}
if (char.ToLower(readchar) == location[offset])
{
offset++;
if (offset >= location.Length)
{
offset = 0;
buffersize = Math.Min(injection.Length, dataOut.Length - dataOutWritten);
if (buffersize > 0)
{
var data = Encoding.UTF8.GetBytes(injection);
dataOut.Write(data, 0, (int)buffersize);
dataOutWritten += buffersize;
}
if (buffersize < injection.Length)
{
var remaining = injection.Substring((int)buffersize, (int)(injection.Length - buffersize));
overflow.AddRange(Encoding.UTF8.GetBytes(remaining));
}
}
}
else
{
offset = 0;
}
}
if (overflow.Count > 0 || offset > 0)
{
return FilterStatus.NeedMoreData;
}
return FilterStatus.Done;
}
/// <summary>
/// Initialization
/// </summary>
/// <returns></returns>
public bool InitFilter()
{
return true;
}
}
Thanks to amaitland for pointing me in the right direction, and for the sample program that the vast majority of the above code was based on. End result:
<html><head></head><body><script>window.InjectedObject = {}</script>
<script>
isObjectPresent = typeof InjectedObject == "object";
</script>
<p>isObjectPresent?</p>
<div id="result"></div>
<script>
document.getElementById("result").innerHTML = isObjectPresent;
</script>
</body></html>
Which meets my needs of pre-processing the document with some text at the top of the header ensuring no timing issues where existing code might be run before the injected code.
edit
couple small fixes. added control logic to only insert when a mainframe is loaded.
Well your answer is correct that you should override the implementation of GetResourceResponseFilter but in case you didn't implement the interface in a correct way you will end up with browser not rendering content, you can instead inherit the DefaultRequestHandler and override the GetResourceResponseFilter() and provide the custom filter as mentioned in the accepted answer, this will be easier in case you need only to ovveride this specific functionality :
public class CustomRequestHandler : DefaultRequestHandler
{
string script = "alert('hello');";
public override IResponseFilter GetResourceResponseFilter(CefSharp.IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
if (frame.IsMain && request.ResourceType == ResourceType.MainFrame)
{
return new JavascriptInjectionFilter(script);
}
return null;
}
}
Then assign it to the chromium browser:
CustomRequestHandler customRequestHandler = new CustomRequestHandler();
chromeBrowser.RequestHandler = customRequestHandler ;

Calling Web Method using Javascript on dynamically created Control

I am creating some controls dynamically in these Dynamic control there is <asp: Image> Control
I want to call webmethod when I click that Image control.I searched a lot but nothing is happening.
the code for Dynamic control is
for (int i = 0; i < SearchResult.Length; i++)
{
System.Web.UI.HtmlControls.HtmlGenericControl panel = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
panel.Attributes["class"] = "panel";
panel.ID = "panel_" + (i + 1).ToString();
System.Web.UI.HtmlControls.HtmlGenericControl inside = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
inside.Attributes["class"] = "inside";
Image img = new Image();
img.ImageUrl = SearchResult[i].ImageUrl;
// img.Attributes.Add("onclick", THE WEB Method I want to call);
inside.Controls.Add(img);
Label label = new Label();
label.Text = SearchResult[i].Title;
label.Font.Size = 10;
label.Font.Bold = true;
panel.Controls.Add(label);
panel.Controls.Add(inside);
test.Controls.Add(panel);
}
and my web method is
[WebMethod]
public static void AddToDownload(String ConnectionString,String Query)
{
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
cmd.ExecuteNonQuery();
con.Close();
}
Get rid of the "onclick" line and wire up a server-side Click event, like this:
protected void Page_Load(object sender, EventArgs e)
{
var img1 = new ImageButton
{
ID = "ImageButton1",
AlternateText = "Button 1"
};
img1.Click += img_Click;
Panel1.Controls.Add(img1);
var img2 = new ImageButton
{
ID = "ImageButton2",
AlternateText = "Button 2"
};
img2.Click += img_Click;
Panel1.Controls.Add(img2);
}
private void img_Click(object sender, ImageClickEventArgs e)
{
var whoClicked = (sender as ImageButton).ID;
}
I have changed your Image server controls to ImageButton server controls to more easily accommodate the Click event.
Each of the two buttons is wired up to a common event handler and then in the event handler it is casting the sender (the control that initiated the event) to an ImageButton and then grabbing its ID to distinguish between the two buttons. You would want to put a null check there in case something besides an ImageButton initiates a click event.
Let me know if you need anything clarified or have further questions.

How to increase or decrease web browser font size using button in windows phone?

Hi am using code given below.I want to increase or decrease text font size on web browser using A+ and A- buttons.i am getting html file from xml feed.so any one help to resolve in this solution.
<phone:WebBrowser x:Name="webBrowser" Height="592" IsScriptEnabled="True" />
<Button BorderThickness="0" Margin="0,0,18,0" Height="88" HorizontalAlignment="Right" Width="96" x:Uid="#aPlus" Click="A-_Click" >
private void A-_Click(object sender, RoutedEventArgs e)
{
if (i > 2)
{
webBrowser.FontSize -= 2;
i++;
j = i;
}
}
private void A+_Click(object sender, RoutedEventArgs e)
{
if (i < 3)
{
webBrowser.FontSize += 2;
i++;
j = i;
}
}
<Fullcontent>
<html>
<body>
<p>When worn right, there’s nothing quite like gold and Shilpa seems to have pulled off the look in style on Nach Baliye 5. Other stars spotted were Ajay Devgn and Akshay Kumar with Kajal Agarwal promoting their film Special 26. Though Kajal looked pretty in an Anarkali, she could not quite compete with Shilpa.</p>
</body>
</html>
</Fullcontent>
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string selectedIndex = "";
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
webBrowser.NavigateToString(App.CurrentArticle.FullContent);
}
}
I am using this code but nothing to change font size.so help me any one how to solve in this solution.
You have to use WebBrowser.InvokeScript:
// Initial text size
int textSize = 100; // Percentage
private void A+_Click(object sender, EventArgs e)
{
textSize *= 2; // Can modify to not increase so much each time
string szfn = "{styleText = \"body { -ms-text-size-adjust:" + textSize + "% }\";styleTextNode = document.createTextNode(styleText);styleNode = document.createElement(\"style\");styleNode.appendChild(styleTextNode);document.getElementsByTagName(\"head\")[0].appendChild(styleNode);};";
webBrowser.InvokeScript("eval", szfn);
}
private void A-_Click(object sender, EventArgs e)
{
textSize /= 2; // Can modify to not decrease so much each time
string szfn = "{styleText = \"body { -ms-text-size-adjust:" + textSize + "% }\";styleTextNode = document.createTextNode(styleText);styleNode = document.createElement(\"style\");styleNode.appendChild(styleTextNode);document.getElementsByTagName(\"head\")[0].appendChild(styleNode);};";
webBrowser.InvokeScript("eval", szfn);
}
Check out this post on MSDN.

Categories

Resources