I have two ASPX pages (P1.aspx and P2.aspx). The first (P1.aspx) contains a lot of JavaScript code.
How can I call all this JavaScript from another page (P2.aspx)?
I tried to do this using PageAsyncTask from code behind of P2.aspx, but JavaScript code (on P1.aspx) didn't work.
Any suggestions?
you cant do that.
put the javascript into JS file and reference it when needed.
What you can do ( I think) is to get the HTML content of the file and then EXTRACT the JS data
edit
try that (I dont think that it will include the inside JS - but try it yourself)
WebRequest oRequest;
WebResponse oResponse;
oRequest = WebRequest.Create("http://www.google.com/");
oResponse = oRequest.GetResponse();
StreamReader sr = new StreamReader(oResponse.GetResponseStream());
string pagedata = sr.ReadToEnd();
pagedata+=#"sdfsdf";
All javascript code you want to use on a page has to be included in that page or dynamically loaded by that page. You cannot call code that is only in another page.
The usual way of sharing code among pages is to have a .js file that contains common code that is included in more than one page and then a .js file that contains code that is unique to each specific page (if required).
One way to do this is <!--#INCLUDE FILE="somefile.aspx" --> but your aspx page will complain that there can be only one 'page' directive. So in order to do this properly you need to include as the previous mentiond the js files in the aspx file.
One way is makeing a master page and include all the necessary js code in there, then all pages that are loaded within the masterpage will automatically inherit the javascript included libraries.
Another way is to make an html file that includes all the libraries and then use the <!--#INCLUDE FILE="myjslibs.html" --> to include all your code there to each page.
So actually copy all your code in one file and then include that just one file each time in every page.
Related
We've been doing my little mail project and I've encountered some problems.
I've been using tomcat and apache so I use jsp right now.
My problem is that I cannot load js file with tag in jsp file.
We want to make kind of single page application so some jsp files are calling other jsp files.
Our jsp file structure is constructed like this way.
box.jsp -> mail-list.jsp -> (select mail from mail list, get mail
content to communicate with server, append at the bottom of the list
and swipe it with animation to show mail contents) -> detail-mail.jsp
In box.jsp, tags are working so I can load java scripts and use it because box.jsp(mail list viewer) shows mail list and all of our java script files are loaded at box.jsp.
But in detail-mail.jsp(show detail mail contents and etc), It doesn't work even though 'detail-mail.jsp' has tags.
Even though css files are loaded, java script files aren't.
Is there any way I can load java script file in this situation?
If I understand correctly: Are you trying to load script tags in an e-mail?
I'm not familiar with JSP, but I have done a fair bit of e-mail development.
You cannot use JavaScript in e-mails, unfortunately. So maybe the <script> tags are being removed from the output of detail-mail.jsp?
You should use these code if you want to load javascripts dynamically with append child.
const s = document.createElement('script');
s.type = 'text/javascript';
s.src = '/js/detail-mail.js';
$('head').append(s);
If you load html after javascripts, javascripts cannot figure out DOM ELEMENTS. So you should load HTML and after that, you shoudl load javascripts.
I have a file index.php and there is a main js script in its header.
I'm using Jquery load method to load other php file inside a div element:
$("#formHideinAjax").load('loginpass.php');
And as our friend explained here the main js file which had loaded in the header doesn't work in new imported file so I was forced to add the js file inside the loginpass.php too(Now I have two same js file, one in header and one in div that loads loginpass.php ! )
I know that this method of loading js file is not standard and sends more request to my server.
How can I fix this problem?
Well, it is explicitly said in $.load() documentation. I'm afraid you can't just paste <script></script> code into your DOM for browser to run it.
I'm afraid you have to send JavaScript code from your loginpass.php file (without <script></script> tags) and just eval it in your JavaScript
$("#formHideinAjax").load('loginpass.php', function () {
// eval JavaScript code from php file here
});
I'm hooking into a separate page (same domain) and pulling it into the current page using $.load, which would be fine, if I was doing it for the whole page, but I'm not, I'm just doing it for the JavaScript code in that page. I was wondering if it's possible to load all the script tags from said page into the current page?
I'm currently using the below code:
var newMessageURL = $('#lnkCompose a').attr('href');
$('#hiddenScriptLoad').load(newMessageURL);
Is said page on the same domain or do you have access to it? You will run into trouble with the cross domain origin policy otherwise.
If you do have access, the only way is to parse the html using a regex statement or html parser and pull the scripts manually.
This sounds like a very hacky approach though and I'm not really sure why you'd want to do this.
If you have access, get the page contents and then use the below to get the script tag sources.
text.match( /<script src="scripts\/(.*?)\.scripts\.js"><\/script>/g )
Credit Javascript regex to get src url between script tag
var newMessageURL = $('#lnkCompose a').attr('href');
$('#hiddenScriptLoad').load(newMessageURL);
The above code will load all the contents you have in the second file and it will also import any javascript codes you have there. But the codes you'll have in second file will not work and wont get into action unless you call to them from first page using a function call or in any other manner.
If you just want to separate your js codings and html and have them in two separate files, it would be better to use PHP to import the second file into the first one and in this way, when the page is loaded in the client browser, it will render it as it was just a single file containing both contents. Ex..
<?php
include("script_file.js");
?>
And also if you want get only the js part of the second file use something like this
<?php
$Vdata = file_get_contents('path/to/YOUR/FILE.php');
preg_match_all("'<script(.*?)</script>'si", $Vdata, $match);
foreach($match[1] as $val)
{
echo $val;
}
?>
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.
I need to be able to save a page on my website to my harddrive, so that i can use it both online and offline. The thing is, the page uses references to javascript and CSS files outside it's own folder. It is very important that i can save the whole page as one .html file, so that all the javascript and CSS code from the external files are in that file as well.
Is there a way to do this?
This should be programatically
As you request, this can be done programmatically with lets say Python.
The pattern of the code would look like this:
Request the user to paste the url in a box
wget or curl the page and use regex to find out where the included codes are
OR: use a library like SGML to interact with the HTML tags directly
Put all the linked CSS, JS etc. files in a List
Fetch all the linked files their contents and put them in a List
Rebuild the HTML source code and strip out the and tags stuff
Now loop the linked files's contents in the tags like this:
newHeaderContent = ''
for content in linkedFilesArray:
newHeaderContent = newHeaderContent + content
newHTML = firstHTMLCode + newHeaderContent + lastHTMLCode