Run javascript file from the workspace in chrome developer tools - javascript

Is it possible to run a newly created JavaScript file in a local workspace in the chrome developer tools console?
The workflow I'm trying to achieve is the one shown in this image:
I want to be able to create a new file in my workspace, run (or require or whatever) the file and be able to use it's functions and variables in the chrome developer console.
If I'm correct, this means running the script within the context of the webpage and adding the methods and variables to the window object?
Is their a way this can be done?

I could not find an automatic way to add a local file into the DOM context. The best solution I found so far:
Open your local workspace and the right file
Press CTRL + a (Select all)
Press CTRL + SHIFT + e (alternative: Right click with the mouse on the selected text and click on "Evaluate in Console")
Well, this is not much better than copy&paste but spares a few key presses/mouse clicks.

You can create a plain html file like this with your javascript file in the script tag.
Then you should be able to get all your methods in the developer console.

You can define a method in your page to dynamically add javascript to the page and then call it from the console.
For example if you had a method like this:
function loadJs(filename) {
var tag=document.createElement('script');
tag.setAttribute("type","text/javascript");
tag.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(tag);
}
then you can use that method from the console to load your javascript files.

As an example:
Step 1: we create one folder "TestJS_folder" and it contains two files.
First file is index.html
Second file is test.js file.
Content of html file can be :
<html>
<head>
<title>Test JS in Chrome</title>
</head>
<body>
<script src="test.js"></script>
</body>
</html>
Step 2: Now you can import/open this test.js file in VSCode or any editor. And you can code the js file from IDE and click on index.html , it will open the html file on browser and you can go to Inspect-> console to check the logs based on your use case.

Related

Notepad++ doesn't open my html file but the google home page

I'm trying to learn html and javascript but I'm having problems opening html files with notepad++.
I downloaded notepad++ and I created a simple html file.
<html>
<body>
Hello world!
</body>
</html>
I uncommented the option to run a file with chrome in the shortcut.xml file.
Finally, I added the chrome link in the notepad++ folder.
When I run the file with chrome, the browser opens the google home page instead of the file.
Whereas, if I write the code in notepad, and I open the file with chrome, the browser opens it up correctly.
I've not set a cloud path yet. Do I have to set one? If yes, which one?
The menu item should say "Launch in Firefox" - corresponding to the name= attribute in the settings file, the fact it isn't means that your likely editing the wrong settings file.
If you have set Settings -> Preferences -> Cloud to a directory then that's where the correct XML file will be, otherwise look in both %APPDATA%\Roaming\Notepad++ & the install dir for other copies of the file.
> what are the best editors for html and javascript
Subjective, but take a look # https://code.visualstudio.com/docs/languages/html
Place the path into quotation marks
<Command name="Edge" Ctrl="no" Alt="no" Shift="no" Key="0">"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" "$(FULL_CURRENT_PATH)</Command>
You shouldn't try to run it from notepad++ itself. Instead, Just Right Click your file from the file explorer and Open with Google Chrome. It should open your file that way.

how to run excel application on html button through browser

i want to make a button in html page so that when a user click it an excel application get starts.
<button class="btn btn-primary" href="to popup excel sheet">click</button>
HTTP is a stateless protocol. What that means for you is that when your users download a file from the intranet via http, they are downloading a copy, rather than the original. Any changes they make will only appear in their copy, and then you end up with loads of copies of the same workbook with different, possibly overlapping changes. You don't want that!
And also ... how are your users even going to upload their changes?
You need to create a shared folder on your network and put the workbook there. You can then use the file:///SERVER/PATH/FILE.xls format in your <a /> links on your intranet to direct your user to the actual file on the server.
I would recommend you start by creating a simple html doc on your desktop to get familiar with the file:/// path format.
Eg
<html>
<head />
<body>
Click
<body>
<html>
save that in notepad and rename the extension from .txt to .html.
You can also type file:/// paths straight into windows explorer's address bar which allow for testing paths without resorting to the html document mentioned above.
UNFORTUNATELY! It seems that the browsers default behavior is to always download a link rather than open it (even if it is a local resource), so if you actually want to open it then you must resort to changing your browser intranet permissions to allow JS to access local resources, which then allows you to use the technique below.
This article (http://www.codeproject.com/Articles/113678/How-to-execute-a-Local-File-using-HTML-Application) uses
<script type="text/javascript" language="javascript">
function RunFile() {
WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("c:/windows/system32/notepad.exe", 1, false);
}
</script>
to open notepad. You can use command line arguments with Excel.exe (https://support.office.com/en-za/article/Command-line-switches-for-Excel-321cf55a-ace4-40b3-9082-53bd4bc10725) to tell it what the file path is...
Excel.exe "C:\PATH\Excel.xls"
Refer link: Open excel file through normal html link

Using external JavaScript files in a WinForms/WPF WebBrowser control

I found a cool feature on a website, implemented in JavaScript, I'd like to use it as is in my desktop application (for personal use).
During my experiments I managed to generate custom HTML on the fly, feed it to the browser using webBrowser1.DocumentText = [my generated HTML]
I've managed to put some inline JavaScript into the HTML, and hook it up via a ScriptManager so that I can call the JavaScript from my C# code, pass a value to it, and get a return value.
But the feature I'm trying to use is a bit more complicated: it's no less than 10 JavaScript files. 2 of them are referenced directly in the web page the usual way <script src="/js/script1.js" type="text/javascript"></script>
The other 8 are loaded in one of the scripts:
var elem = document.createElement("script");
elem.type = "text/javascript";
elem.src = "/js/" + filename;
document.body.appendChild(elem);
These 8 files are in fact data files, even though the data is represented in JavaScript. They're pretty large, over 1MB each. Stuffing it all into the HTML file seems quite stupid. Also, the script that loads the data creates a "file map" and further refers to the data based on which file it's in:
var fileMap = [
[/[\u0020-\u00ff]/, 'file1.js'],
[/[\u3000-\u30ff]/, 'file2.js'],
[/[\u4e00-\u5dff]/, 'file3.js'],
...
I don't want to resort to modifying the JavaScript, because it's not exactly my strong point. So the browser needs to "see" the js files in order to be able to use them. I thought of creating the file structure locally, and navigating the browser there. But I don't want any loose files in my solution. I'd like to have everything embedded if possible. And I doubt I can get the browser to navigate to an embedded resource, and see other embedded resources as files. Any idea how I could get around this?
EDIT:
I've tried to do it with local files. No luck. I get the HTML to load properly, but when I try to invoke a JavaScript call, nothing happens. I tried pointing the browser to those js files, to make sure they're there. They are. I tried an element with src attribute pointing to an image in the same subfolder as the script files. It gets rendered. It's as if external js files refuse to load.
I had a similar need as your scenario and I addressed it using two key points embedded in two other Stack Overflow answers. As noted by SLaks' answer here the first key is using the syntax file:/// as the prefix for an absolute path to external files. The second is using .Replace("\\", "/") for an absolute file path as listed in Adam Plocher's answer and one of his follow-up comments here.
In short, the final output for each external file in an HTML page will look something like:
<link href="file:///c:/users/david/myApp/styles/site.css" rel="stylesheet" type="text/css">
or
<script src="file:///c:/users/david/myApp/scripts/JavaScript1.js"></script>
Using the format in the samples above in my HTML file resulted in the WebBrowser control loading external CSS, image or script files.
The details and solving the scenario in the question
In the womd's answer in the first referenced SO answer above he used the method System.IO.File.ReadAllText() to load script files and embedded the text of the script files into the <head> tag. As you indicated in your question loading script files directly into the HTML page is not what you're looking to do.
The solution below involves using the same System.IO.File.ReadAllText() method but loads the text of the HTML page instead. The premise works similar to the Razor View Engine in ASP.NET.
The main idea in the solution below involves adding a temporary string in an HTML page that will be loaded into the WebBrowser control and then replacing this temporary string in a C# method in my app just before the HTML page is set to be loaded into the WebBrowser control.
Here are the basic steps to my solution:
Add a temporary string for each external reference in the HTML file.
Declare a variable for the absolute path in a script tag within the HTML file. This step is not necessary unless you're going to use the absolute path elsewhere within your JavaScript code. Your scenario involves delay loading external script files via JavaScript code so this step was necessary.
Modify the src property in the JavaScript code that delay loads the other script files with the absolute path variable.
Add a method in your app to loads the HTML page file as a text string and then replaces all temporary string instances with an absolute path containing the prefix 'file:///'. The absolute path should have forward slashes.
Set the 'DocumentText' property on the WebBrowser control to the updated HTML.
Set the 'Copy to Output Directory' of each external file in your project to 'Copy always' or 'Copy if newer'. This step may not be necessary if you have a fixed location to your external files and that location is not within the build or publish directory used by Visual Studio.
The following are the details for each step. I added a lot of detail that you can skip. I was verbose to reduce any confusion since the steps make changes to several places in the project.
1. Using a temporary string
I used the string "/ReplaceWithAbsolutePath/" but you can use any distinct text. Each reference to an external file in the HTML page looks like:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<link href="/ReplaceWithAbsolutePath/styles/site.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
var absolutePath = "/ReplaceWithAbsolutePath/";
</script>
</head>
<body>
<p>My web page</p>
<script src="/ReplaceWithAbsolutePath/scripts/JavaScript1.js"></script>
</body>
</html>
2. Declare absolute path variable
Note in the above HTML page I listed a <script> tag with the declared variable 'absolutePath' set to the temporary string. (In the HTML page above the variable is added a global variable and that is not necessarily best practice. You can declare the variable within a namespace instead of declaring it in the global namespace.)
3. Modify the delay load script to include absolute path variable
Add the 'absolutePath' variable to your JavaScript file that delay loads other JavaScript files containing your data.
elem.src = absolutePath + "/js/" + filename;
4. C# method to replace all temporary string instances
Within your project add the following line to your form load event handler or place this line somewhere in your initialization of the WebBrowser control.
webBrowser1.DocumentText = GetUpdatedHtmlWithAbsolutePaths("/ReplaceWithAbsolutePath/", "HTMLPage1.html");
Add the following method to your code. Update the call to the method in the line above with the name of the class instance where the following method is placed.
// The result of this method will look like the following example:
// <script src="file:///c:/users/david/documents/myApp/scripts/JavaScript1.js"></script>
public string GetUpdatedHtmlWithAbsolutePaths(string tempPathString, string htmlFilename)
{
// Get the directory as the application
// stackoverflow.com/questions/674857/should-i-use-appdomain-currentdomain-basedirectory-or-system-environment-current
// Note that the 'BaseDirectory' property will return a string with trailing backslashes ('\\')
string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
// Replace '//' with '/' in the appDirectory string
appDirectory = appDirectory.Replace("\\", "/");
// Read all of the HTML text from the HTML page file
string html = System.IO.File.ReadAllText(appDirectory + #"\" + htmlFilename);
// Replace all '/ReplaceWithAbsolutePath/' strings within the HTML text with
// the absolute path on the local machine
html = html.Replace(tempPathString, "file:///" + appDirectory);
return html;
}
5. Set the DocumentText property of the WebBrowser control
I added the initialization of the WebBrowser control in the form load event handler but you can, of course, add the line that sets the DocumentText property wherever you initialize your WebBrowser control.
private void Form1_Load(object sender, EventArgs e)
{
// Set the document text of the web browser control with the updated HTML
webBrowser1.DocumentText = GetUpdatedHtmlWithAbsolutePaths("HTMLPage1.html");
}
6. Set the 'Copy to Output Directory' of each external file
Take a look at the answer posted by Matthew Watson in this Stack Overflow question if you want your external files included in your solution/project file structure.
You can add files to your project and select their properties: "Build
Action" as "Content" and "Copy to output directory" as "Copy Always"
or Copy if Newer (the latter is preferable because otherwise the
project rebuilds fully every time you build it).
Then those files will be copied to your output folder.
This is better than using a post build step because Visual Studio will
know that the files are part of the project. (That affects things like
ClickOnce applications which need to know what files to add to the
clickonce data.)
In short, add the external file to your project. You can add the external to any subfolder in your project. (In Visual Studio 2013 or 2015 -- I don't have VS2012) Right-click on the external file in the Solution Explorer and select Properties from the context menu. The Properties pane will be displayed. In the Properties pane change the setting for 'Copy to Output Directory' to 'Copy always' or 'Copy if newer'.
Use View Source to verify absolute path strings
Run your project and it should load your external files in the WebBrowser control. Assuming you have not set the property wbChartContainer.IsWebBrowserContextMenuEnabled = false; in code or in the Properties pane for WebBrowser control you can right-click on the WebBrowser control when your form is running. Click 'View Source' from the context menu and check the paths to your external resources in the View Source window.

javascript object expexted

I am unable to call a javascript function as it says "Object Expected". I am using asp.net and this is being used on a standard aspx page with some usercontrols. One of the user controls called CookieControl calls a javascript method setandCheckCookie() on document.ready.i.e
$(document).ready(function() {
setandCheckCookie();
)};
In the head section on my aspx page I have reference the javascript file before I add the control:
<script src="CookiesControl/js/Cookie.js" type="text/javascript"></script>
<uc2:Cookie ID="Cookie1" runat="server" />
I've event tried adding the script reference on the user control itself but when I go to my aspx page I get the object expected error.
I don't believe its the control or the js file as both these are used elsewhere in the website and they work fine but something I'm doing is stopping the js file from being reference because in firebug and IE debugger I can't see the referenced js file.
Perhaps the path is incorrect but I have dragged the script from the solution explorer and visual studio isn't complaining about the path either.
So my question is: what could potentially stop my javascript file from being referenced.
Visual Studio complaining or not about a path is not always saying what you'll get in the browser. To check if the script is referenced ok, try to get the script file in the browser. For example, if you page is at http://yoursite/yourpage.aspx and your script reference in the html code (by View Source, not what you see in Visual Studio) is folder/scriptFile.js, put this address http://yoursite/folder/scriptFile.js and see if you get the file. If not, then it is not referenced ok.
To solve issues like that, put the full path after yoursite, like:
<script src="/ScriptVirtualFolder/CookiesControl/js/Cookie.js" type="text/javascript"></script>
where ScriptVirtualFolder is in your site root folder, and it is a virtual folder, means it is accessible by the browser in this path.
Also, you can use asp.net to resolve your path by using the ~ sign and runat='server'. For example:
<script src="~/ScriptServerFolder/CookiesControl/js/Cookie.js" type="text/javascript" runat="server"></script>

Edit external JavaScript file after breakpoint is hit

In the VS2010 IDE when a breakpoint (or an error) is hit, it opens a read-only [dynamic] version of the external JavaScript file I referenced. My workflow would be vastly improved if I could immediately edit this file, and refresh the browser. That is as opposed to digging up the original JS file opening it, finding the correct line and editing there.
I only know that this is possible because I was able to do this on my old work computer configuration, but for the life of me I can't duplicate it at home.
Has anyone made this work? Perhaps an extension? or maybe it has to with the way the files are referenced, or my basehref tag, or url rewriting.
This happens when the base href specifies a domain other than localhost. My issue was that to enable a local environment for Facebook JS, I need my domain in the url. So I set up my host file to remap localhost.mydomain.com to localhost.
When the Visual Studio IDE encounters a file reference which is something other than localhost, it does not attempt to grab the local file since it assumes (correctly in most cases) that it is being served from another site. In these cases it loads a file as [dynamic] and readonly.
Here is the test case:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<base href="http://localhost.mydomain.com/virtual-directory/" />
<script type="text/javascript" src="test.js"></script>
</head>
<body>
</html>
Any breakpoint within test.js will result in opening a readonly dynamic file.
how are you referencing your files? whenever a script block is written inside the html or is dynamically inserted the debugger will open the instance of the page where the code stops. If you reference the script using tags vs should open the original script file (at least that's what it does on my machine). could you upload an example of your current structure?

Categories

Resources