Make $location.path open in the same frame (target = "_self") - javascript

In a mean-stack web application with html5mode, I have defined the following angular-ui-router
.state('addinHome', {
url: '/addin/home',
template: "home page"
})
Then, I have another page https://localhost:3000/test/ with a button button. Also in its controller, I have
... ...
$location.path("/addin/home")
... ...
Normally, both $location.path and the button lead to https://localhost:3000/addin/home.
Now, I add the following references in index.html:
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
<script src="https://cdn.rawgit.com/devote/HTML5-History-API/master/history.js"></script>
It disturbs the ui-router. As a consequence, both $location.path and the button lead to https://localhost:3000/test/#%2Faddin#%2Fhome, which is NOT what I want.
I have found the solution to fix the button: it is using button (opens the linked document in the same frame as it was clicked; see here).
However, I have not found the solution to fix $location.path("/addin/home"). Could anyone help?

Inject $window as dependency.
Try using $window.open(URL,"_self")

Related

Page reloads when clicking anchor element

I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.
I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".
I'm not sure what's causing the whole page to reload.
Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.
I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.
It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like
<a href="#" (click)="$event.preventDefault()">
Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:
Html
<a href="#" (click)="someFunc($event)">
and in your ts:
someFunc(event) {
event.preventDefault();
// rest of your code here
}
This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.
I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.
So, my work around is:
#HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}
Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.
change your a tag code as below
A Tag
this will invoke yourClickEvent(); without page reload
check the stackblitz here stackblitz
If you don't want to reload the page use $event.preventDefault()
<a href="#" (click)="$event.preventDefault()">
Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.
You could also simply paste this into the console to trigger a break, and then click any of the offending elements:
['unload', 'beforeunload'].forEach(function (evName) {
window.addEventListener(evName, function () {
debugger; // Chance to check everything right before the redirect occurs
});
});
source: Break when window.location changes?
As you are using angular routes, try to use this notation:
<a [routerLink]="['./']" fragment="Test">
As explain by this comment: https://stackoverflow.com/a/38159597/4916355
use href="javascript:void(0);"
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.
ex:
// downloading the file based on file name
<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
Since you have mentioned the web app is asp.net webforms, can you please let us know
Whether the link is asp.net hyperlink control. If so,
AutoEventWireUp could cause the link to be automatically submitted:
Please have a look at this link
If you do have asp.net server controls on the page, then you could disable by setting
#Page AutoEventWireup="false"
For the entire project, this can be disabled by setting in web.config:

Ionic 2 tabs double tap

I have a dynamic tabs page in my Ionic2 app that looks like this:
<ion-tabs #myTabs class="tabs-md" type="md" [tabsHighlight]="true" [selectedIndex]="mySelectedIndex">
<ion-tab *ngFor="let tab of tabRoots" [root]="tab.page" [tabTitle]="tab.name" [tabIcon]="tab.icon"></ion-tab>
</ion-tabs>
When the user taps on a tab that is already selected and is therefore the root page already, the page will still reload. The issue is that I have a few custom animations that rerun when this happens. So I want to disable the ability to navigate to your same root page.
I've tried putting
ionViewCanLeave() {
return //viewchild of #myTabs and returns true if next page does not equal current page.
}
This worked in that it stopped the refresh of the current root page, but the app crashes when navigating to another page that isnt a root (a child page) because myTabs reference is undefined.
Any advice on how to accomplish this? I would prefer to handle this from my tabs controller.
Try : ionSelected() {
// DO SOMETHING OR NOT
}
In your 'HomePage' for example.
Links : https://forum.ionicframework.com/t/capturing-ion-tab-click-on-active-tab-event/56594/27
I Hope I could help you.
This was caused by a bug in ionic which was fixed in version 3.0.1
https://github.com/ionic-team/ionic/pull/11084

Content navigation breaks after first level

Currently I have setup a small test application and ran into some trouble lately. After some tries I still don't know where my mistake is.
Here is my pen: http://codepen.io/ins0/pen/wtELa
The problem is that after clicking the side navigation the content normally shows up, navigation updates. When I click on a link inside the content - the url state changes (eg. from #/settings to #/settings/about, xhr gets fired and received but the content doesn't get replaced.
I tried listening to all state events but no error is thrown.
I found the mistake by myself. In order to get the navigation correct you need to set a a viewtarget in your router configuration for childen pages that point to your parent view. Like this:
state('app.settings.about', {
url: "/about",
views: {
'content#app' :{
templateUrl: "about.html"
}
}
});
see'content#app'. this tells the framework to render the about view in the content field defined in route app. I updated the codepen to a working example.

How to add a JSP page dynamically on click

I have a link like follows :
<font size="2"><a class="pull-right" id="pageAdd" href="" title="add new page"><i
class="icon-plus-sign"></i></a></font>
and a jquery script as follows
<script type="text/javascript">
$(document).ready(function(){
$("#pageAdd").click(function() { .................(1)
$.get('WEB-INF/views/diary/createPage.jsp', function(data) {
$("#newPage").html(data);
});
});
});
I am trying to add the createPage.jsp to the following div
<div id="newPage">
</div>
I have debugged using firebug. The execution is going inside the jquery but jumping out after line 1. Any idea what is the problem.
Your JavaScript seems to be okay. At marker (1) you add a function to the onClick Event. When you debug in Firebug, you probably only see your function being added, not being called.
The Link WEB-INF/views/diary/createPage.jsp looks odd to me. Your war file will not serve anything to a browser from inside the WEB-INF directory.
Try moving the file outsite WEB-INF, rebuild your app and test in your browser, if you can manually browse to http://localhost:8080/YOUR_CONTEXT/views/diary/createPage.jsp
Open Firebugs Network view: Can you see a request to views/diary/createPage.jsp? Maybe your JavaScript sends the request to the wrong path due to how relative path are calculated
Your WEB-INF folder is not visible to HTTP calls, try to make the $.get() using /views/diary/createPage.jsp
I think you should also either change the href from "" to "#" or return false in the onclik, otherwise the browser could reload the page and break the script execution.

How can I log a hyperlink click?

I have a hyperlink which I need to log when it's clicked.
I created a small prototype, and the problem is repeatable by creating a new MVC 2 Web app project.
Add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
to the Site.Master file.
And
public ActionResult LogSomething()
{
string doNothing = DateTime.Now.ToString();
return new EmptyResult();
}
to the HomeController.cs file
And
<p>
<a id="lnkTestPost" href="/home/about">Test Post</a>
<script type="text/javascript">
$("#lnkTestPost").click(function() {
$.post("/home/LogSomething");
});
</script>
</p>
in Home/Index.aspx
Put a break point in the LogSomething() action method in the HomeController.
But when I run it, sometimes the breakpoint is hit, other times it isn't.
I'm assuming it's not being hit due to the actual link sending the browser to another page, but shouldn't the post be made before the link is fired?
Is there anyway I can ensure the logging code is fired?
Please note; adding the logging functionality in the link target is not an option.
EDIT: The original hyperlink is actually to a custom protocol for an app installed on the user PC. So the link is to something like "myapp:myArgs". I didn't mention that in order to keep things simple, unfortunately, since none of the answers really apply to me, I now think it's necessary to mention.
If I were doing it, I would probably do what, eg, Google does and setup a URL which logs then redirects. For example:
stuff
<script>
$("a:href").each(function(){
this.attr("href", "/log?url=" + encodeURIComponent(this.attr("href")));
});
</script>
Then /log handler would do something like:
def log(request):
target_url = request.GET["url"]
log_link(target_url)
return HttpRedirect(target_url)
You'd need to put some thought into dealing with external links (eg, how you want to handle http://example.com/log?url=http://evil.com/)… But that's a solvable problem.
Also, for bonus points, you could swap the URL as the link is clicked (this is what Google does in their search results), so the mouse-over link-preview looks correct.
Alternatively, you could do what Google Reader does, and put a "from url" in each link:
<script>
$("a:href").each(function(){
this.attr("href", this.attr("href") + "?from=" + encodeURIComponent(window.location));
// (note: this exact code won't handle links which already have GET vars…)
});
</script>
Then use some middleware to log the "from" in inbound requests.
This has the disadvantage that it won't be able to log clicks going to another domain… But that might be alright.
I think the browser could easily navigate to the URL before logging the click. How about:
<p>
<a id="lnkTestPost" href="#">Test Post</a>
<script type="text/javascript">
$("#lnkTestPost").click(function() {
$.post("/home/LogSomething", function(data) {
// only tell the browse to navigate away once its logged
window.location = '/home/about';
});
});
</script>
</p>
An approach that I have seen used by many sites, including google, is to have a "redirector" page, so all the links go through that page/controller, you log it, then from there you can redirect them
How 'bout an optional "log" parm on each page that is included as part of the links so you don't have to have any Javascript at all? Granted, each page could be logging something from the referrer page, but it shouldn't care, since you could have it just pass off whatever's in the log parm to the logging infra and go on.

Categories