MicrosoftEdge / MicrosoftEdge/WebView2Feedback

Why function at AddScriptToExecuteOnDocumentCreatedAsync is called only after source change ?

Open
#1,426 5 comments 0 reactions 1 assignee View on GitHub

@vbryh-msft is already working on this.

Since Jun 23, 2021.

bug priority-low tracked
Dominant language
PowerShell
Stars
526
Forks
67
PR merge metrics
No merged PRs in 30d

Description

I have a simple application with WebView2.
In my InitializeAsync method, I add 2 scripts via AddScriptToExecuteOnDocumentCreatedAsync.

async void InitializeAsync()
		{
			await webView.EnsureCoreWebView2Async();
			webView.CoreWebView2.WebMessageReceived += RecievedMessage;
			webView.CoreWebView2.DOMContentLoaded += delegate
			{
				IsDOMLoaded = true;
			};

			await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("document.addEventListener('mouseup', function(event) { var res = window.getSelection().toString(); var myObj = {action: 'Selection', data: res}; var json = JSON.stringify(myObj); if(res.length > 1) { window.chrome.webview.postMessage(json); } }, false);");

			await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(
				"function getTextHTML(){var res = document.body.innerText; var myObj = {action: 'GetHTML', data:res}; var json = JSON.stringify(myObj);window.chrome.webview.postMessage(json);}");
		}

Then after button click which should Execute the second script - nothing happens.

private async void ButtonClick(object sender, RoutedEventArgs e)
		{
			await webView.CoreWebView2.ExecuteScriptAsync("getTextHTML();");
        }

But first await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("document.addEventListener.... works fine at start page.
In order to call my second function, I need to reload a page or go to another page.

My question is:

Why it has such behavior and how can I fix it?

Besides, I'd like to know, how I can ensure that script was added? Once, I found my script somewhere after clicking F12 on my browser, but I can't find it again now.

AB#33935614

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.