My Javascript is poor, but I have made a site with subpages that are loaded by revealing divs using Javascript functions: http://thenethersphere.com/ Observe the Gateway page is loaded by default, which is fine.
My objective is to determine which of the three URL is being requested by the client, e.g. #gateway (default), #comms, or #library and trigger the requisite function to actually load a subpage if the user goes to, e.g. thenethersphere.com/#comms or thenethersphere.com/gateway.vs#comms would cause the page to run showComms(), which looks basically like this:
function showComms() {
hideGateway();
hideLibrary();
document.getElementById("comms").style.left = "11em";
document.getElementById("comms").style.visibility = "visible";
document.getElementById("lcarsmain1").style.color = "#FF9900";
document.getElementById("lcarsmain2").style.color = "#FF9900";
document.getElementById("lcarsmain3").style.color = "#FF9900";
}
Use the location.hash to get the relevant part of the url and call the appropriate function ..
example
var section = location.hash.slice(1);
if (section == 'comms') showComms();
Related
So i am working on a Userscript and there is one major step i'm trying to find the easiest resolve with since i am very new to Javascript coding...I'm trying to perform/code a function that will open a specified URL:
EXAMPLE: Homepage ("http://www.EXAMPLE.com")
(page can be opened as 'Window.open' = Blank, or _self);
...when the parent or (current) URL that is open
EXAMPLE: innner.href = ("www.EXAMPLE.com/new/01262016/blah/blah/blah");
...has a text on the HTML documnt page that reads:
EXAMPLE TEXT from page ("www.EXAMPLE.com/new/01262016/blah/blah/blah");:
"this is the end of the page, please refresh to return back to homepage"
(TEXT: not the real keyword, but want to use phase as a detection for a setTimeout function to return back to home.)
Any help will be much appreicated, you guys are veryinformative here. Thanks in advance.
I think I have the gist of you question. It is a straighforward, though quite intensive, task to scan the entire text content of a page for specific keywords with JavaScript. However, if the keywords appear more than once (on multiple pages that should not redirect) then your users will get undesirable results.
A simple solution would be to add a class="last-page" attribute to the body-tag of the final page and run a function that checks for this. Something like....
HTML
<body class="last-page"><!--page content--></body>
JS
window.onload = function() {
var interval = 5000; // five seconds
if (document.body.classList.contains('last-page')) {
setTimeout(function() {
window.location.assign('http://the-next-page.com/');
}, interval);
}
};
Alternatively, if you have the ability to wrap the specified text in a uniquely identified html-tag, such as...
<span id="last-page">EXAMPLE TEXT</span>
...then the presence of this tag can be checked on each page load - similar to the function above:
window.onload = function() {
var interval = 5000;
if (document.getElementById('last-page') {
setTimeout(/* code as before */);
}
};
Yet another solution is to check the page URL against a variable...
window.onload = function() {
var finalURL = 'http://the-last-page.com/blah/...';
if (window.location === finalURL) {
/* same as before */
}
};
If this kind of thing is not an option please leave a comment and I'll add a function that gathers a pages entire text content and compares adjacent words to a pre-defined set of keys.
I was asked to take a look at what should be a simple problem with one of our web pages for a small dashboard web app. This app just shows some basic state info for underlying backend apps which I work heavily on. The issues is as follows:
On a page where a user can input parameters and request to view a report with the given user input, a button invokes a JS function which opens a new page in the browser to show the rendered report. The code looks like this:
$('#btnShowReport').click(function () {
document.getElementById("Error").innerHTML = "";
var exists = CheckSession();
if (exists) {
window.open('<%=Url.Content("~/Reports/Launch.aspx?Report=Short&Area=1") %>');
}
});
The page that is then opened has the following code which is called from Page_Load:
rptViewer.ProcessingMode = ProcessingMode.Remote
rptViewer.AsyncRendering = True
rptViewer.ServerReport.Timeout = CInt(WebConfigurationManager.AppSettings("ReportTimeout")) * 60000
rptViewer.ServerReport.ReportServerUrl = New Uri(My.Settings.ReportURL)
rptViewer.ServerReport.ReportPath = "/" & My.Settings.ReportPath & "/" & Request("Report")
'Set the report to use the credentials from web.config
rptViewer.ServerReport.ReportServerCredentials = New SQLReportCredentials(My.Settings.ReportServerUser, My.Settings.ReportServerPassword, My.Settings.ReportServerDomain)
Dim myCredentials As New Microsoft.Reporting.WebForms.DataSourceCredentials
myCredentials.Name = My.Settings.ReportDataSource
myCredentials.UserId = My.Settings.DatabaseUser
myCredentials.Password = My.Settings.DatabasePassword
rptViewer.ServerReport.SetDataSourceCredentials(New Microsoft.Reporting.WebForms.DataSourceCredentials(0) {myCredentials})
rptViewer.ServerReport.SetParameters(parameters)
rptViewer.ServerReport.Refresh()
I have omitted some code which builds up the parameters for the report, but I doubt any of that is relevant.
The problem is that, when the user clicks the show report button, and this new page opens up, depending on the types of parameters they use the report could take quite some time to render, and in the mean time, the original page becomes completely unresponsive. The moment the report page actually renders, the main page begins functioning again. Where should I start (google keywords, ReportViewer properties, etc) if I want to fix this behavior such that the other page can load asynchronously without affecting the main page?
Edit -
I tried doing the follow, which was in a linked answer in a comment here:
$.ajax({
context: document.body,
async: true, //NOTE THIS
success: function () {
window.open(Address);
}
});
this replaced the window.open call. This seems to work, but when I check out the documentation, trying to understand what this is doing I found this:
The .context property was deprecated in jQuery 1.10 and is only maintained to the extent needed for supporting .live() in the jQuery Migrate plugin. It may be removed without notice in a future version.
I removed the context property entirely and it didnt seem to affect the code at all... Is it ok to use this ajax call in this way to open up the other window, or is there a better approach?
Using a timeout should open the window without blocking your main page
$('#btnShowReport').click(function () {
document.getElementById("Error").innerHTML = "";
var exists = CheckSession();
if (exists) {
setTimeout(function() {
window.open('<%=Url.Content("~/Reports/Launch.aspx?Report=Short&Area=1") %>');
}, 0);
}
});
This is a long shot, but have you tried opening the window with a blank URL first, and subsequently changing the location?
$("#btnShowReport").click(function(){
If (CheckSession()) {
var pop = window.open ('', 'showReport');
pop = window.open ('<%=Url.Content("~/Reports/Launch.aspx?Report=Short&Area=1") %>', 'showReport');
}
})
use
`$('#btnShowReport').click(function () {
document.getElementById("Error").innerHTML = "";
var exists = CheckSession();
if (exists) {
window.location.href='<%=Url.Content("~/Reports/Launch.aspx?Report=Short&Area=1") %>';
}
});`
it will work.
This is the algorithm of what I want to do:
1.Locates flickr links with class' high_res_link and puts them in array [].
2.Opens flickr link with extension "sizes/h/"
3.finds largest photo dimensions on flickr. Then goes to that link. Or if there arent any big enough goes to step 2 and goes to next
array.
4. then opens link to download if downloading is enabled. If not goes to step 2 and goes to next array.
5. Goes to step 2 and goes to next array.
I am trying to write some code that crosses two domains: Tumblr and Flickr.
I have currently written 3 functions with Jquery and Javascript which I want to run on 2 different URLs:
Function #1:
function link_to_flickr() {
var hre = [];
$('.high_res_link').parent(this).each(function(){
var h = $(this).attr('href') +"sizes/o/";
hre.push(h);
});
alert(hre[0]);
}
This finds the links on the Tumblr page to the Flickr pages I want. And puts them in an array.
Function #2:
function find_large_quality() {
var w = 1280;
var h = 720;
var matchingDivs = $("small").each(function () {
var match = /^\((\d+) x (\d+)\)$/.exec($(this).text());
if (match) {
if (parseInt(match[1], 10) >= w && parseInt(match[2], 10) >= h) {
return true;
}
}
return false;
});
var href = $.trim(matchingDivs.text()).match(/\(.*?\)/g);
if (matchingDivs.length >= 1) {
alert("success");
} else {
alert("fail");
}
var ho = $('small:contains("'+href[href.length - 1]+'")').parent(this).find("a").attr("href");
alert("http://www.flickr.com"+ho);
}
This function once on the Flickr URL then searches for an image with dimensions greater than 720p.
Function #3:
function Download(){
var heyho = $('a:contains("Download the")').attr('href');
window.open(heyho, '_blank');
}
This downloads the image file. Once on the Highest quality Flickr URL
Each alert I want to open the URL instead. And perform the next function on. I have been trying for ages and ages of a method to go about doing something like this.
Using AJAX, using PHP, using Jsonp, using jquery.xdomainajax.js, etc... But I can't come up with a sufficient method on my own.
Has anybody got any way they would recommend going about doing something like this?
You usually can't run functions on different domains due to CORS unless the domains allow that.
If you're writing a userscript/extension, what you can do is use postMessage (quick tutorial on how to use it cross-domain) on both pages in a content script and use the achieved inter-page communication to control your script flow.
An alternate method is to use the APIs of the websites you want to access.
Or use Python with BeautifulSoup.
What I want to do is to run go() function in image.js file. I've googled around and I understand that is not possible to run inline scripts.
What is the best method to call the JavaScript I want? Events? Messages? Requests? Any other way?
Here is my code so far:
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
var viewTabUrl = chrome.extension.getURL('image.html');
var newURL = "image.html";
chrome.tabs.create({
url : newURL
});
var tabs = chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; i++) {
var tab = tabs[i];
if (tab.url == viewTabUrl) {
//here i want to call go() function from image.js
}
}
});
});
image.html
<html>
<body>
<script src="js/image.js"></script>
</body>
</html>
image.js
function go(){
alert('working!');
}
There are various ways to achieve this. Based on what exactly you are trying to achieve (which is not clear by your question), one way might be better than the other.
An easy way, would be to inject a content script and communicate with it through Message Passing, but it is not possible to inject content scripts into a page with the chrome-extension:// scheme (despite what the docs say - there is an open issue for correcting the docs).
So, here is one possibility: Use window.postMessage
E.g.:
In background.js:
var viewTabURL = chrome.extension.getURL("image.html");
var win = window.open(viewTabURL); // <-- you need to open the tab like this
// in order to be able to use `postMessage()`
function requestToInvokeGo() {
win.postMessage("Go", viewTabURL);
}
image.js:
window.addEventListener("message", function(evt) {
if (location.href.indexOf(evt.origin) !== -1) {
/* OK, I know this guy */
if (evt.data === "Go") {
/* Master says: "Go" */
alert("Went !");
}
}
});
In general, the easiest method to communicate between the background page and extension views is via direct access to the respective window objects. That way you can invoke functions or access defined properties in the other page.
Obtaining the window object of the background page from another extension page is straightforward: use chrome.extension.getBackgroundPage(), or chrome.runtime.getBackgroundPage(callback) if it's an event page.
To obtain the window object of an extension page from the background page you have at least three options:
Loop through the results of chrome.extension.getViews({type:'tab'}) to find the page you want.
Open the page in the first place using window.open, which directly returns the window object.
Make code in the extension page call a function in the background page to register itself, passing its window object as a parameter. See for instance this answer.
Once you have a reference to the window object of your page, you can call its functions directly: win.go()
As a side note, in your case you are opening an extension view, and then immediately want to invoke a function in it without passing any information from the background page. The easiest way to achieve that would be to simply make the view run the function when it loads. You just need to add the following line to the end of your image.js script:
go();
Note also that the code in your example will probably fail to find your tab, because chrome.tabs.create is asynchronous and will return before your tab is created.
I need to open up a .aspx page in a modal dialog. Here is the JS code I use to open the dialog:
if (url) {
var fullPath = url + "/Validation.aspx";
}
else {
alert("Could not find the location of the merge dialog. Please contact your System admin and have them update the configuration entity.");
return;
}
var features = "unadorned:yes;scroll:yes;resizable:yes;status:yes;dialogHeight:480px;dialogWidth:480px;";
var args = {
selected: selectedIds,
page: pageIds,
fetchXml: xml,
entity: "xyz"
};
window.showModalDialog(fullPath, args, features);
In my validation.aspx page I need to be able to grab the JS arguments, assign them to hidden fields, then repost, so I can use those arg values server side.
here is my JS code in my .aspx page:
window.onload = function(){
if (!window.dialogArguments)
return;
var args = window.dialogArguments;
...
}
I have seen tons of examples of this working throughout the web. But...My window.dialogArguments is always undefined in my .aspx page. What gives? anyone have any thoughts or solutions?
My assumption here is that the ASPX dialog page is being opened cross-domain.
This would mean that your parent page is in one domain aka: http://abc/page.html, and that your child dialog page is in another domain like: http://def/dialog.html.
If this is the case, it seems as though there are restrictions against accessing dialogArguments and returnValue. Check out the comments on this previous answer for example.