Execute js script into Windows 10 webView - javascript

I'd like to run a js function that is not written into loaded html page, for example we have a simple html page with button, and I'd like to disable the button using an external js script:
<!DOCTYPE html>
<html>
<body>
<button id="my_button" type="button" onclick="">Click Me!</button>
</body>
</html>
and I have my script form a file:
function disableFun() {
document.getElementById("my_button").disabled = true;
}
as is mentioned in official doc there is a API method InvokeScriptAsync(string scriptName, string[] arguments) but is mentioned that we must already have the script into html loaded page.
Any advices are apreciated!
P.S. in android we do it very simple webView.loadUrl('my script code')

You can use InvokeScriptAsync with the JavaScript eval function to inject content into the web page.
see Interacting with WebView content section of this document.
So to disable the button, you can use the following codes in your cs file:
String scriptStr = #"document.getElementById('your_buttonId').disabled=true";
await myWebView.InvokeScriptAsync("eval", new String[] {scriptStr});

Related

UWP Webview ScriptNotify is not getting trigerred

Need to get callback from webpage to my "WebView" in C# using scriptnotify. But it's not working.
I hosted a webpage locally using node js. Webpage is as below.
<!DOCTYPE html>
<html>
<body>
<h1>The onclick Event</h1>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "latest";
window.external.notify('The script says the doubled value is ' );
}
</script>
</body>
</html>
After that created a UWP app to open the webpage using webview. Added window.external.notify in the JS to get the call back. But not getting the same.
//C# code to get the callback
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
//Added the notification handler here
webView.ScriptNotify += webView_ScriptNotify;
//Navigating to the local page
webView.Navigate(new Uri("http://localhost:8080/"));
}
async void webView_ScriptNotify(object sender, NotifyEventArgs e)
{
//Kept break point here , but it's not getting hit any time.
var jsScriptValue = e.Value;
Debug.WriteLine("Send to debug output.");
}
}
//Added a web view control in xaml file
<Grid>
<WebView x:Name="webView" Height="500"> </WebView>
</Grid>
UWP Webview ScriptNotify is not getting trigerred
Please check WebView document.
To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's URI in the ApplicationContentUriRules section of the app manifest. (You can do this in Microsoft Visual Studio on the Content URIs tab of the Package.appxmanifest designer.) The URIs in this list must use HTTPS, and may contain subdomain wildcards (for example, https://.microsoft.com) but they cannot contain domain wildcards (for example, https://.com and https://.). The manifest requirement does not apply to content that originates from the app package, uses an ms-local-stream:// URI, or is loaded using NavigateToString.
So, you need add your uri to the content uri option.

How to use external html file in current html code

I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});

How to run .exe file or .bat file based on button click event using Javascript

In my current project, I would like to run .bat or .exe file using button click event using JavaScript. The content of batch file is as shown below:
start "S:\" TemperatureSensor.exe
which start TemperatureSensor.exe file when TemperatureSensor button is clicked.
Code for HTML page is shown below:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="window.open('file:///S:/Test.bat')">Temperature Sensor</button>
</body>
</html>
When I clicked on Temperature Sensor button, it should run Test.bat file but it just display following in new page:
Am I missing ?? Is it possible to run .exe file using button click event??
Updated:
Code for HTML page is shown below:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="myFunction()">Temperature Sensor</button>
<script>
function myFunction() {
var oShell = new ActiveXObject("Shell.Application");
var commandtoRun = "C:\\TemperatureSensor.exe";
if (inputparms != "") {
var commandParms = document.Form1.filename.value;
}
// Invoke the execute method.
oShell.ShellExecute(commandtoRun, commandParms, "", "open", "1");
}
</script>
</body>
</html>
When I clicked on Temperature Sensor button it displays error: Uncaught ReferenceError: ActiveXObject is not defined.
Just save this code as RunExe.hta and not RunExe.html and executes it by double click on it !
EDIT : REMARK about (HTA) (HTML Application)
HTML Application (HTA) is a Microsoft Windows program whose source code consists of HTML, Dynamic HTML, and one or more scripting languages supported by Internet Explorer, such as VBScript or JScript.
The HTML is used to generate the user interface, and the scripting language is used for the program logic.
A HTA executes without the constraints of the internet browser security model; in fact, it executes as a "fully trusted" application.
further reading about HTA HTML Application
<html>
<head>
<title>Run Exe or Bat files from HTA by Hackoo</title>
<HTA:APPLICATION
APPLICATIONNAME="Run Exe or Bat files from HTA by Hackoo"
ID="MyHTMLapplication"
VERSION="1.0"/>
</head>
<script>
function RunExe(){
var shell = new ActiveXObject("WScript.Shell");
var path = '"S:/Test.bat"';
shell.run(path,1,false);
}
</script>
<input style="width: 170px; height:23px; color: white; background-color: #203040;
font-family:Book Antiqua;" type="button" Value="Temperature Sensor" onClick="RunExe();"
</html>
If you're using firefox you could use this addon to open batch or exe files.
Exe and batch files aren't opening in browser by default becaue of security restrictions.
In a later version of the addon there will be an enable preference for exe-files and these files will be disabled by default.
But at the moment you can create links like test and launch the file with a click.

Chrome Extensions: Pass data from popup to another script file before the script is injected

Problem
Let's assume I go to a website called RENT.com. Let's also assume for this chrome extension there is a script A (JS) that is injected to RENT.com. Script A is a large script file that does a lot of interacting with RENT.com's HTML elements such as form fields. Before the script runs however, it needs some DOM ID's of a couple elements such as the email field because it modifies them.
Objective
I'd like to create a couple input fields (let's call them InputEmail and InputName) in popup.html to enter in the ID's of the elements on RENT.com. Obviously I'd be looking up the ID's manually by viewing the source, this is intentional.
A button in popup.html let's call it "GO BUTTON" will then read the value of InputEmail and InputName and send it to Script A. Script A now has everything it needs to function properly and is now injected into the page.
The appropriate interactions from Script A and RENT.com are now completed.
I've tried a few things, read a ton of information from Docs and Stack but I don't understand I think fundamentally how this can work. I want to pass data to Script A via popup.js before I execute content_script which ultimately is just injecting Script A. Seems like a chicken/egg problem and I'm not hungry for breakfast or lunch ;).
Thanks guys!
popup.html
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
</head>
<body>
<ul>
<li><label>Email ID</label><input type="text" id="emailID"></input></li>
<li><label>Company ID</label><input type="text" id="nameID"></input></li>
</ul>
<input type="button" id="Modify" style="" value="GO BUTTON"></input>
<script src="popup.js"></script>
</body>
</html>
Popup.js
function click(e) {
//Ideally pass these values to Script A somehow
var email = document.getElementById("emailID").value;
var company = document.getElementById("nameID").value;
//then execute this or pass the ID's to content_script, inject into Script A, then inject into page
chrome.tabs.executeScript(null, {file:"contentscript.js"});
window.close();
}
document.addEventListener('DOMContentLoaded', function () {
var d = document.getElementById("Modify");
d.addEventListener('click',click);
});
ContentScript to inject Script A
var s2 = document.createElement('script');
s2.src =chrome.extension.getURL("ScriptA.js");
s2.async = false;
s2.onload = function() {
s2.parentNode.removeChild(s2);
};
(document.head||document.documentElement).appendChild(s2);
There are several ways to accomplish this. One would be:
function click(e) {
var elementIDs = {
email: document.getElementById("emailID").value,
company: document.getElementById("nameID").value
};
chrome.tabs.executeScript({
code: 'window.elementIDs='+JSON.stringify(elementIDs)
}, function() {
chrome.tabs.executeScript({file: "ScriptA.js"});
});
window.close();
}
This way, ScriptA will be able to access the values in window.elementIDs. This will work because content scripts from the same extension on the same page will share the execution environment, and the chaining of the calls to chrome.tabs.executeScript ensures that the script defining the global variable has run before ScriptA is run.

Javascript - Dynamically load a fragment of HTML and run script

I'm building a webpage and I want to re-use some HTML I have elsewhere on my website. The page I am building (index.html) can dynamically get and insert the HTML I want (existing.html) using XMLHttpRequest. However, the HTML I want to get is populated by some Javscript. That Javascript is not being executed when I load it into my new page:
index.html:
<html>
<head>
<script type = "text/javascript">
... //use XMLHttpRequest to load existing.html
initExistingHTML(); //this is function which populates loaded HTML, is not executed
</script>
</head>
<html>
existing.html:
<div>
<script type = "text/javascript">
function initExistingHTML() {
... // do some stuff
}
</script>
</div>
How can I load existing.html and run the script which populates it?
Once the page has loaded, add in existing.html via innerHTML. Rather than calling its functions, just let existing.html's code execute, which will do the same as if it were in the onload section.
EDIT: Or, you could just correct that typo you have. initExistingHTML != initExistingHtml.
lol

Categories

Resources