I am trying to write a Greasemonkey/Tampermonkey script which tracks URL changes. (similar to polling approach mentioned here)
However, I would like to extend a bit such that if the page has Angular I would rather subscribe the routing events instead of polling. (How to detect a route change in Angular?)
Is it possible to subscribe to Angular events from userscripts?
I am working with a script that looks like it is trying to do that in this block... but doesn't seem to properly detect the route.
const updateTragetOnState = (state) => {
if (state.vssNavigationState?.routeId !== "ms.vss-code-web.create-pull-request-route") {
// only work on create-pull-request-route
return;
}
For the record, that codeblock is not my own. It is a portion of a script sample submitted by Pei-Tang Huang for the purpose of working with modifying a pull request selection in Azure Devops. And in my case, it does not work.
Related
I'm very very new to node.js, but there's actually only one simple thing that I am trying to achieve by learning the language.
I'd like to create a webpage, where by the code in a specific "div" can be hotswapped on the fly to users currently looking at that page. (ie. the div contains some text, but then an image replaces it.)
Ideally, the swap would be executed manually by the the webpage's admin through the click of a button, or some code fired off on the server or something. Regular viewers to the webpage would not be able to do this - they only see the live changes on the page.
real-life example:
live internet broadcast is off-air, therefore the "div" contains "off-air" text.
live hotswap of code happens when broadcast goes on-air, and the viewers of the webpage now see the html5 broadcast player in the "div" instead.
What's the simplest way to go about doing this for a node.js newbie?
Many thanks :)
Take a look at Socket.IO http://socket.io/#how-to-use
when the server decides to broadcast a change use:
io.sockets.emit('update-msg', { data: 'this is the data'});
on the client first connect socket.io and then wait for the "update-msg" event and update your dom:
var socket = io.connect('http://localhost');
socket.on('update-msg', function (msg) {
console.log(msg);
$('#mydiv').html(msg.data)
});
I created a system/methodology to live update (hot reload) front-end code using RequireJS and Node.js. I made sure it worked with both React and Backbone. You can read about it here:
https://medium.com/#the1mills/hot-reloading-with-react-requirejs-7b2aa6cb06e1
the basic steps involved in doing this yourself:
gulp.js watchers listen for filesystem changes
socket.io server in gulpfile sends a message to all browser clients
with the path of the file that changed
client deletes cache representing that file/module, and re-requires
it (using AJAX to pull it from the server filesystem)
front-end app is configured / designed to re-evaluate all references
to the modules that it wishes to hot-reload, in this case, only JS
views, templates and CSS are available to hot reload - the router,
controllers, datastores (Backbone Collections and Models) are not
configured yet. I do suspect all files could be hot reloaded with
the only exception being data stores.
I'm using Angular 5 for building a web application and would like to know if I can re-initialize the entire application OR use something like:
ApplicationRef.tick();
to execute all the changes that happens after a specific event. The event is my scenario is authentication token renewal, because for some reason my application's change detection starts breaking unless I run each action inside
NgZone.run()
(I'm using ADAL for authentication in case anybody is interested), but when the token is renewed (using a hidden iframe) the application change detection, routing, etc starts breaking. But when the page is refreshed it starts working perfectly fine till the next time token expires and ADAL has to create an iFrame to renew the token. So I was thinking if at least I could re-initialize the application after the token is renewed so that user doesn't have to refresh the application manually (till I find a more solid solution).
You can call the change detection explictly like below.
constructor(private changeDetector: ChangeDetectorRef) {
this.someEvents.subscribe((data) => {
this.changeDetector.detectChanges();
} );
}
https://angular.io/api/core/ChangeDetectorRef
It's mandatory, if you are calling any third party API or executing third party library Codes. We need to manually call ngzone.run(), which will internally call ApplicationRef.tick() to notify angular to perform change detection from Application root component to the child component (i.e whole application).
ngZone.run(()=>{
// Adal callback Function
});
If you are need to trigger change detection only to the current component and their childrens (not whole application). You can use any one option.
1) setTimeout(()=>{}, 0);
2) this.cdr.detectChanges();
3) For Components with OnPush Change Detection Stratergy, you can call this.cdr.markForCheck() inside setTimeout();
setTimeout(()=>{
this.cdr.markForCheck();
}, 0);
I have a small webapp in Node/Express that renders initial HTML server side with react-dom. The page is then populated client side with a $.ajax call to the API inside componentDidMount. The HTML loads immediately, but there's no useful content until React starts and completes that GET.
This is wasteful. It would be better to hit the API while rendering the initial HTML. But. I don't know a clean way to implement this. Seems like I could get what I want by declaring a global $ in node with a stubbed get method, but this feels dirty.
How do I implement $.ajax when rendering a React component server side?
The code is public on Github. Here's a component with $.get and here's my API.
componentDidMount doesnt run on the server, it runs only client side for the first render, so the ajax request will never happen on the server. You should do it in a static method (there are other ways of do it)
It would be better if you choose superagent or axios - that can made ajax requests client and server side
You then have to put the result of the ajax request as the initial state on a global variable.
It's better if you follow some repos, like this:
See https://github.com/erikras/react-redux-universal-hot-example
Here's how I solved this.
Moved my ajax out of componentDidMount so that it is called while rendering initial HTML on the server.
Declared my own global $ in Node with a get method that calls the router directly. This is what it looks like:
global.$ = {
get: (url, cb) => {
const req = {url: url};
const res = {
send: data => cb(data),
status: () => {
return {send: data => cb(data)};
}
};
return api_router(req, res);
}
};
Some caveats
If this feels like a questionable hack to you, that's ok. It feels like a questionable hack to me too. I'm still open to suggestions.
#stamina-loop's suggestion of replacing jQuery's AJAX with module that works for both the server and client is a good one that would solve this problem. For most people I would recommend that approach. I chose not to because it seemed wasteful to go over the network just to call a route handler that is adjacent in code. Could be made less wasteful with a fancy nginx config that redirects outbound API calls back to the same box without making a round trip. I'm thinking on that.
I've since learned that using jQuery alongside React is likely to cause problems. I'll be replacing it with something else down the road.
For most use cases it will still make sense to keep the AJAX in componentDidMount and to load initial HTML without it. That way time-to-first-byte is as low as possible. The types of things that are loaded from restful APIs are usually not needed for SEO and are things that users are used to waiting a few extra milliseconds for (Facebook does it so can you).
I am working on a very basic SPA using Backbone.js. My app has few routes. Among them there are 2 that give me issues: the index route ("/#index") and menu route ("/#mainmenu").
A simple workflow in my app is as follows: the user fills a form -> clicks to login -> trigger ajax request -> if login successful go to "/#mainmenu" route. if login failed, remain on "/#index" route.
On "/#mainmenu" if the user clicks on logout -> ajax request -> if logout success go to "/#index". if logout failed remain on "/#mainmenu".
The issues that I am struggling with are:
A clean way to trigger transition to "/#mainmenu" after successful login (I currently use router.navigate("mainmenu", {trigger: true}); but read that should avoid using this approach, in derrick bailey's article https://lostechies.com/derickbailey/2011/08/28/dont-execute-a-backbone-js-route-handler-from-your-code/ )
A clean way to prevent the user to go back to the "/#index" when pressing Back button in the browser from "/#mainmenu" route. I will also would like to preserve the url hash to reflect the current view.
Prevent the user to go forward to "/#mainmenu" after successful logout.
Is that even possible to prevent url hash change when clicking browsers back/forward buttons?
When I say "clean" I refer to "what are the best practices?". I partially solved some issues by saving url hashes and restore the appropriate hash (by router.navigate(currentRoute, {replace: true}); ) but I feel that it's a hacky approach.
Any feedback is welcome and much appreciated.
One way to solve this problem is by applying an async before filter on the routes that require an auth status check before the actual callback route is executed.
For example:
https://github.com/fantactuka/backbone-route-filter
The philosophy of avoiding {trigger: true} is based on the fact that when the router gets triggered with this flag, the entire initialization procedure for that route gets triggered. You will lose the benefit of having previously defined appstates because the app will have to re-initialize all content while this work had alrady been done before.
In practice, I think that it is useful to assess what your web app actually does. If losing appstate isn't an issue because the views you want to render are entirely new, then I don't see a problem with creating a client side redirect that re-inintializes your app.
If, on the other hand, your app has many views already rendered for which you want to maintain the same state as before, you can listen for an auth state event on each component that requires it, and make only those views re-render accordingly if they need to.
I don't think there's anything wrong with triggering routes, have been doing this without any issue for 2+ years. It all boils down to your requirements, read the article looks like a lot of work to me.
There are multiple ways to do this. First, you can disable back/forward buttons using window.history.forward(). Second, my favourite, is to do the processing in Router#execute. A sample might look like :
execute: function(callback, args, name) {
if (!loggedIn) {
goToLogin();
return false; //the privileged route won't trigger
}
if (callback) callback.apply(this, args);
}
I have a small application where a users can drag and drop a task in an HTML table.
When user drops the task, I call a javascript function called update_task:
function update_task(user_id, task_id, status_id, text, uiDraggable, el) {
$.get('task_update.php?user_id='+user_id+'&task_id='+task_id+'&status_id='+status_id+'', function(data) {
try {
jsonResult = JSON.parse(data);
} catch (e) {
alert(data);
return;
};
In task_update.php I GET my values; user_id, task_id & status_id and execute a PDO UPDATE query, to update my DB. If the query executes correctly, I
echo json_encode ( array (
'success' => true
) );
And then I append the task to the correct table cell
if(typeof jsonResult.success != 'undefined') {
$(uiDraggable).detach().css({top: 0,left: 0}).appendTo(el);
}
This has all worked fine. But, I'm starting to realize, that it's a problem when 2 or more people are making changes at the same time. If I'm testing with 2 browsers, and has the site opened on both for example: Then, if I move a task on browser1, I would have to manually refresh the page at browser2 to see the changes.
So my question is; How can I make my application auto-detech if a change to the DB-table has been made? And how can I update the HTML table, without refreshing the page.
I have looked at some timed intervals for updating pages, but that wouldn't work for me, since I really don't want to force the browser to refresh. A user can for example also create a new task in a lightbox iframe, so it would be incredibly annoying for them, if their browser refreshed while they were trying to create a new task.
So yeah, what would be the best practice for me to use?
Use Redis and its publish/subscribe feature to implement a message bus between your PHP app and a lightweight websocket server (Node.js is a good choice for this).
When your PHP modifies the data, it also emits an event in Redis that some data has changed.
When a websocket client connects to the Node.js server, it tells the server what data it would like to monitor, then, as soon as a Redis event was received and the event's data matches the client's monitored data, notify the client over the websocket, which then would refresh the page.
Take a look at this question with answers explaining all of this in detail, includes sample code that you can reuse.
I would use ajax to check the server at a reasonable interval. What's reasonable depends on your project - it should be often enough that it changes on one end don't mess up what another user is doing.
If you're worried about this being resource intensive you could use APC to save last modified times for everything that's active - that way you don't have to hit the database when you're just checking if anything has changed.
When things have changed then you should use ajax for that as well, and add the changes directly in the page with javascript/jquery.
If you really need to check a db changes - write a database triggers.
But if nobody, except your code, change it - you can to implement some observation in your code.
Make Observation(EventListener) pattern imlementation, or use one of existed.
Trigger events when anything meaningful happened.
Subscribe to this events