How detect that all JavaScripts completed in GeckoWebBrowser - javascript

I use GeckoWebBrowser component for get some webpages. But I don't know when page JavaScripts fully completed.
For detecting page full load I use event DocumentCompleted.
private GeckoWebBrowser wb = new GeckoWebBrowser();
private bool doc_loaded = false;
wb.DocumentCompleted += Browser_DocumentCompleted;
doc_loaded = false;
wb.Navigate(url);
Wait_Load();
private void Browser_DocumentCompleted(object sender, EventArgs e)
{
doc_loaded = true;
}
private void Wait_Load()
{
while (doc_loaded == false)
{
Application.DoEvents();
Application.RaiseIdle(new EventArgs());
}
}
How detect that all JavaScripts completed in GeckoWebBrowser?

Related

Unable to read CefSharp Chromium console message

I have a WinForm application that using cefsharp web browser. From what I learnt about cefsharp, the events MouseDown, Click cannot trigger in WinForm. So I decided to use javascript to send a message to the console, and trigger ChromiumWebBrowser.ConsoleMessage event instead. But that did not work well. Did I mess up the javascript code or execute the code wrongly?
Here are the codes, please noted that UI.cs is a Form object. A panel object pn_Browser already created in the design view. What I tried to do is, click any element and send "success" to the console. Then the Background show the received message if the message in console.log is "success".
Background.cs
public ChromiumWebBrowser browser;
public Background()
{
browser = new ChromiumWebBrowser("https://www.google.com");
browser.ConsoleMessage += browser_ConsoleMessage;
browser.FrameLoadEnd += browser_FrameLoadEnd;
}
public void browser_ConsoleMessage(object sender, ConsoleMessageEventArgs e)
{
if (e.Message == "success")
{
System.Windows.Forms.MessageBox.Show("Received message.");
}
}
public void browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
Chromium.ExecuteScriptAsync("document.addEventListener(\"click\", function() {alert('Detect a click.');});");
}
UI.cs
public UI()
{
InitializeComponent();
Background background = new Background();
pn_Browser.Controls.Add(background.browser);
background.browser.JavascriptMessageReceived += browser_JavascriptMessageReceived;
background.browser.ExecuteScriptAsyncWhenPageLoaded(
"function test() {console.log(\"success\")}" +
"document.addEventListener(\"click\", test);"
);
}
delegate void JavascriptReceivedCallback(object sender, JavascriptMessageReceivedEventArgs e);
private void browser_JavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
if (InvokeRequired)
{
JavascriptReceivedCallback callback = new JavascriptReceivedCallback(Browser_JavascriptMessageReceived);
Invoke(callback, new object[] { sender, e };
}
else
{
MessageBox.Show(e.Message.ToString());
}
}

OnServerClick with dynamic anchorlink not firing

I'm trying to fire an OnServerClick event from some anchor tag created dynamically. My event isn't firing from my anchor tag. i have no error.
Can someone help me ?
HtmlAnchor btn_close = new HtmlAnchor();
btn_close.Attributes.Add("class", "close");
btn_close.Attributes.Add("data-dismiss", "alert");
btn_close.Attributes.Add("aria-label", "Ne plus afficher");
btn_close.Attributes.Add("title", "Ne plus afficher");
btn_close.Attributes.Add("runat", "server");
btn_close.ServerClick += new EventHandler(hideNotificationBtn_Click);
btn_close.ID = notificationSent.NotificationSentID.ToString();
btn_close.InnerText = "test";
div_alert.Controls.Add(btn_close);
protected void hideNotificationBtn_Click(object sender, EventArgs e)
{
HtmlAnchor cb = (HtmlAnchor)sender;
int test = int.Parse(cb.Name);
NotificationSent.SetNotificationAsHidden(int.Parse(cb.Name));
}
My hide notification isn't fired from by anchor when i click on it.
I already tried to change it to a button.
Thank you for your help.
Anchors don't call server side functions even when they are runat server, however there is the LinkButton class that can be used instead. Ultimately it is rendered as JavaScript initiated postback. Check out https://forums.asp.net/p/1519048/3644158.aspx for more information.
Make sure you are creating that button early enough in the page lifecycle. Look to get it created OnInit of the Page.
This is because the event handling events happen after Page Init. Of course, the button has to have been created before the events can be detected on
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["falg"] != null)
{
Create();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Create();
ViewState.Add("falg", true);
}
void BtnServices_Click(object sender, EventArgs e)
{
Response.Write("hi");
}
void BtnServices_Command(object sender, CommandEventArgs e)
{
Response.Write("hi");
}
void Create()
{
BtnServices = new Button();
BtnServices.ID = "BtnServices";
BtnServices.Text = "Click Me";
BtnServices.Click += new EventHandler(BtnServices_Click);
BtnServices.Command += new CommandEventHandler(BtnServices_Command);
form1.Controls.Add(BtnServices);
}
Easier and reliable way to do this could be , instead of dynamically
adding the control, always add it, but set Visible=false initially.
Then where you're currently adding it, instead just make it visible.

What is preventing Javascript from execution?

Neither of the Javascript function is executed in "btnrepeat()", although I have called another javascript in page_load event and that is working fine
C#
protected void Button1_Click(object sender, EventArgs e)
{
Timer1.Enabled = true;
workerThread = new Thread(new ThreadStart(btnrepeat));
workerThread.Start();
}
protected void btnrepeat()
{
ClientScript.RegisterClientScriptBlock(GetType(), "mys", "abcd()", true);
for (int i = 1; i <= filecount; i++)
{
string trnsfrpth = #"E:\\ProjectLocalPath\" + filename;
last_file++;
balance_load(filename, trnsfrpth);
Thread.Sleep(200);
}
ClientScript.RegisterClientScriptBlock(GetType(), "mytts", "abcd()", true);
//Label1.InnerHtml = last_file.ToString();
//This is not aspx label, but an HTML div
//this is possible actually but not working here
}
Javascript
function abcd() {
alert('hello');
}
Function is doing what it is supposed to, so there is no logical mistake.
And I've also tried,
ClientScript.RegisterStartupScript(GetType(), "mytts", "abcd()", true);
And The last 3 lines commented is another problem, it doesn't work...why ?

JavascriptInterface function crashing javascript on web page

I have a webview in my android app. I want to show a banner only if the web page is viewed on browser. I created an interface and it tests fine but because the web page doesn't recognize the function the other javascript on the page doesn't load. Here is my Code:
Interface Class
import android.content.Context;
import android.webkit.JavascriptInterface;
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public Boolean getUser() {
return true;
}
}
Activity Class
public class MainActivity extends Activity {
ProgressBar progressBar;
WebView webview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.webview);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
webview.addJavascriptInterface(new WebAppInterface(this),"Android");
this.webview.getSettings().setUserAgentString(
this.webview.getSettings().getUserAgentString()
+ " "
+ getString(R.string.user_agent_suffix)
);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if (progress == 100) {
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.VISIBLE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webview.loadUrl("http://www.getonfleek.com");
ParsePush.subscribeInBackground("test");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
}
}
HTML
</script>
<script type="text/javascript">
$(document).ready(function(){
var user = Android.getUser();
if(user == null){
//do something on web
}else{
//do something in app
}
});
</script>
Check to make sure the interface exists before trying to call it.
<script type="text/javascript">
$(document).ready(function(){
var user = null;
if(typeof Android !== 'undefined'){
user = Android.getUser();
//do something in app
}else{
//do something on web
}
});
</script>

Inject JavaScript in Android after WebView has finished loading from a previous JavaScript Injection

I have a Webview, that onPageFinished injects some JavaScript, this JavaScript populates the form on this page and submits the form successfully.
My question is how do i then check for onPageFinished of the page the WebView goes to after the form has been submitted? As i wish to inject some more JavaScript to pull out some values.
Thanks in advance.
You need to manage yourself redirection through a flag that you manipulate in all 3 relevant methods:
boolean loadingFinished = true;
boolean redirect = false;
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
view.loadUrl(urlNewString);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap facIcon) {
loadingFinished = false;
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
#Override
public void onPageFinished(WebView view, String url) {
if(!redirect){
loadingFinished = true;
}
if(loadingFinished && !redirect){
//HIDE LOADING IT HAS FINISHED
} else{
redirect = false;
}
}
});

Categories