.load function went wrong if there is anchor (#) in URL - javascript

My page have some parts that will be populated by .load()
$(document).ready(function() {
if (document.getElementById('add_to_userlist')) {
$('#add_to_userlist').load(script_name + '?' + nv_name_variable + '=' + nv_module_name + '&' + nv_fc_variable + '=v_funcs&mod_list=user_playlist' + '&id={DETAIL.id}' + '&fcheck={DETAIL.check_session}' + '&nocache=' + new Date().getTime());
}
if (document.getElementById('favourite-{DETAIL.id}')) {
$('#favourite-{DETAIL.id}').load(script_name + '?' + nv_name_variable + '=' + nv_module_name + '&' + nv_fc_variable + '=v_funcs&mod_list=get_fav' + '&id={DETAIL.id}' + '&fcheck={DETAIL.check_session}' + '&nocache=' + new Date().getTime());
}
$(".bodytext_shorten").shorten({showChars: 200});
});
Everything is okay but if there is an anchor in this URL, like :
http://nukeviet-hvt.rhcloud.com/videos/chuyen-muc-1/sau-tim-thiep-hong-giao-linh-ft-tuan-vu-2.html#comment_box
The page does not load as it should. The div with id id #add_to_userlist and favourite-{DETAIL.id} load entire of page instead of a HTML part only.
So the page keep reload and enable my flood blocker.
I think there is a conflict but don't know how to solve it.
Google Chrome show this in Console
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check https://xhr.spec.whatwg.org/.

The jQuery load method doesn't support fragment identifiers in URLs to determine which part of a document to load.
The syntax it supports is a space followed by a CSS selector.
.load("http://nukeviet-hvt.rhcloud.com/videos/chuyen-muc-1/sau-tim-thiep-hong-giao-linh-ft-tuan-vu-2.html #comment_box")
It isn't entirely clear from the question, but it looks like you have that value in script_name and then are trying to add the query string after it.
In a URL the query string must appear before the fragment identifier.
In load() syntax, the selector must appear after the entire URL (i.e. after the query string and after any fragment identifier).

Related

Browser shortcut - add url

I needed to help with a feature I have never seen before. I do not even know if it exists, but you may have met.
I'm referring to the shortcuts in the browser and I would like to add another shortcut to "add 'this' to the end of the url".
Example:
I am on www.example.com and click on the link in the shortcut bar to redirect me to www.example.com/redir1. If I'm on www.example2.com and click on the same link, it redirects me to www.example2.com/redir1.
I manage a number of sites and I have to click on "Settings/blah blah/page/" takes a few minutes. By linking, I would like to get straight to the "page" so I do not have to click and load pages before this one so many times.
You may use a Bookmarklet.
Bookmarklets are (small) chunks of JavaScript, that will be executed when clicking the bookmarked link. I use them for quick navigation in ticket systems.
Maybe this example solves your problem.
Of course, you have to condense your JavaScript to just one line, so it fits into the address line of the bookmark.
javascript:(function(){open(window.location.protocol + "//" + window.location.hostname + "/redir1");})();
You can even open a JavaScript prompt for retrieving some kind of user input. The next example asks the user where he wants to go and modifies the link respectively.
javascript:(function(){var relPath=prompt('Where do you want to go?'); open(window.location.protocol + "//" + window.location.hostname + "/" + relPath);})();
I tested this one in the current versions of Firefox and Chrome. Just add a new bookmark and use the JavaScript Code instead of any URL.
Additional examples, as requested in comments.
For the sake of readability, I present the second one in multiple lines, please remove the line breaks before trying to use it as a bookmarklet.
The first example navigates from
protocol://sub.domain.tld/any/possible/path/somewhere.xyz to
protocol://sub.domain.tld/web1/site/site.xml.
javascript:(function(){open(window.location.protocol + "//" + window.location.hostname + "/web1/site/site.xml");})();
The second example navigates from
protocol://sub.domain.tld/keep/this/any/site.xml to
protocol://sub.domain.tld/keep/this/another/resource.
If window.location does not contain a long enough path name, the navigation will not work, because the script will just add "undefined" in the target URL.
javascript:(function(){
var pathNameAsArray = window.location.pathname.split('/');
var pathToKeep = "/" + pathNameAsArray[1] + "/" + pathNameAsArray[2];
open(window.location.protocol + "//" + window.location.hostname + pathToKeep + "/another/resource");})();

Capture incoming URL parameters & pass into a div's "data-url" attribute

We are currently using a typeform that is embedded in our site. All of the traffic driven to our site is from cpc campaigns so accurate conversion tracking in GA is a must so we can accurately track our ROI.
Here's the problem. When sending cpc campaigns to the directly to the typeform URL the GA tracking was accurate. After embedding the typeform into our site the GA tracking shows that the referrer is our site, and not Google or Bing cpc.
Without making this too long of a post, I need to be able to capture the campaign parameters (utm source, utm medium, etc) in the URL & input that data into a "data-url" attribute located in a div.
Right now this is the code i have:
function main () {
var loc = window.location.toString(),
params = loc.split('&')[1],
params2 = loc.split('&')[2],
params3 = loc.split('&')[3],
params4 = loc.split('&')[4],
params5 = loc.split('&')[5],
typeformWidget = jQuery("#typeformWidget");
typeformWidget.attr('data-url') == typeformWidget.attr('data-url') + '?' +
params + '&' + params2 + '&' + params3 + '&' + params4+ '&' + params5;
console.log(params);
};
main();
I appears that the correct parameters are being captured when I see the data in the console, however I cannot for the life of me figure out how to pass the data to the "data-url" attribute.
typeformWidget.attr('data-url', typeformWidget.attr('data-url') + '?' +
params + '&' + params2 + '&' + params3 + '&' + params4+ '&' + params5);
OR
typeformWidget.data('url', typeformWidget.data('url') + '?' +
params + '&' + params2 + '&' + params3 + '&' + params4+ '&' + params5);
The reason your code does not work is that == is used to compare equality usually used in if statements. To assign a value you use = but with jQuery you need to use the method to assign the value in this case .attr('attribute name', value) or the .data('name after the data-', value)
Classes and names have changed in the latest versions of Typeform this is how I got it to work.
You will need to load jQuery, this one or latest version:
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
Then you basically just take the URL in JavaScript and split the part you want and then replace the URL that loads the embebed form to pass the UTM tag of the initial website , then add this script before </body>:
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
//this where your utm tags should be going given your URL looks like: https://www.whatever.com?utm_source=Facebook you can
//build your URLs here: https://ga-dev-tools.appspot.com/campaign-url-builder/
const utm_source = urlParams.get('utm_source')
typeformWidget = $("[data-url]");
//the hidden field's name you created at typeform must go here, for this example the field is named: 'source',
newurl=typeformWidget.attr('data-url')+'?source='+utm_source;
//you need to load jquery for this
$("[data-url]").attr("data-url", newurl);
</script>
Υou can add more fields but you need first to get them (check above) and then adjust the new url line, it would be typeformWidget.attr('data-url')+'?source='+utm_source+'?medium='+utm_medium etc. etc.;
Github for the script

Save and update information in the Url

I have two carousels, each with their own id "sliderId", and then i have an id on all the elements within the carousel, so i know how far they have scrolled, "currentFirstId".
I would like to save the indformation in the url, and I have done that by writing:
window.location.href = currentLocation + "#" + sliderId + "=" + currentFirstId;
that give me the result i whant: www.blabla.com/#sliderId?2296=0#sliderId?2337=0
But how do git it to update currentFirstId when I scroll, because as it is now, it's put's the information after already existing text like this:
www.blabla.com/#sliderId?2296=0#sliderId?2337=1#sliderId?2296=0#sliderId?2337=2#sliderId?2296=1#sliderId?2337=3#sliderId?2296=2#sliderId?2337=4.
So how do i get it to update the already existing text, so the output is:
www.blabla.com/#sliderId?2296=2#sliderId?2337=4 ???
I hope it makes sense.
Maybe try:
window.location.href = window.location.hostname + window.location.pathname + '#' + sliderId + '=' + currentFirstId;
Look at this Post:
URL without query string
Maybe you want to use window.location.origin and append the "#sliderId?2296=0#sliderId?2337=0" part to that rather that using currentLocation.

Is there any way to AccessAll the search history of Browser with out using any API [duplicate]

If i click on the history tab on my browser I can reach a folder with all of the links ive visited organized by date.
How can I access this programmatically with Javascript? I'm still new to Javascript but I want something like:
var aListOfDateLinkPairs = window.history.some_get_list_function;
I'm sure this is a big privacy issue for some arbitrary entity but what If I want to implement this (programmatically) for myself in my own browser?
Thanks!
In general history is protected by the browser against javascript accessing it except through back and forward functionality. There are some hacks that can view some amount of history, but they are just that--hacks.
If you want to view/modify history programatically, you could do so via browser plugins. For example, Chrome plugins can use this API
EDIT
Mozilla also has some info about history modification available to Javascript here.
It also looks like this question talks about some of the same things you need.
Javascript only offers basic calls once your page takes control of the browser like:
history.length
window.history.back()
history.forward()
window.history.go(-3)
But if you were to write your own browser then you'd be using a 3GL in which case you'd be in total control of what the user has typed in the search or address fields you provided so you shouldn't have any problems there keeping a record of what the user did if you know what you're doing.
Short Answer no, you cannot access the history of your browser via common Javascript.
You could create an extension that would be cross browser with something like: http://crossrider.com/
The Docs for accessing the Places storage, which enables you to access the history of the browser is here for firefox: https://developer.mozilla.org/en-US/docs/Using_the_Places_history_service
And for chrome it is here: http://developer.chrome.com/extensions/history.html
There is a file for Places called Places.sqlite is an sqlite database, if you would build a local application that reads from that file, instead of accessing it from your browser, that would be simpler in my opinion.
You could also use the https://addons.mozilla.org/en-us/firefox/addon/sqlite-manager/ sqlite manager and order the history according to dates directly from the database. Here's an ERD for that http://people.mozilla.org/~dietrich/places-erd.png
The URI place: schema provides a modicum of potential for the javascript "only" (mousing around required) solution given below.
First note the distinction between session history, which can be accessed via History and window.history, and the overall browser history (in FF this is known as part of the library and another library part being bookmarks) which has no direct javascript access interfacing.
ref:
Places query URIs | MDN
History - Web API Interfaces | MDN
Window.history - Web API Interfaces | MDN
on the web: developer.mozilla.org/en-US/docs/Web/API/Window.history
tested with:
window.navigator.userAgent=
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4
(Splashtop-v1.2.17.0)
(The intimate familiarity with this subject is unfortunately due to the severely crippled FF released as QuickWeb by Device VM in the Splashtop system.)
Here is what can be done:
Note:
the FF test environment identified above - some of the "conventions"
used maybe exclusive and not universally available in other browsers
or FF versions
at the expense of a little more manually labour intensive intervention than
1 a simple activation click ...
the solution suggested here also requires
2 a bookmark link click
3 save it click
4 ~ 6 bookmark open and select sequence
7 results drag & drop
8 ~ 10 cleanup and delete results from bookmarks
(is not this anathema to the whole precept of the Order of Automata aka computer automation?
js js is js - Just Saying JavaScript is Just [too] "Simple")
Using javascript construct a place: scheme URI with the appropriate .some_get_list_function and bookmark it.
extract history
Clicking the link fails but right click bookmarking it and then clicking the bookmark "succeeds". Ergo, might as well resolve left click to redirect immediately to bookmark.
extract history
Drag and drop the now bookmarked place: URI "hystryx" into a target <form><textarea> . Note a significant limitation is that this process retrieves ONLY the history's URI's and none of the history chronology, titles, etc. It is possible to recover some of this information (such as titles by opening each URI to extract them, doing so of course changes the URI "most recent access date" in the history) to render the URI as "nice" links.
Putting it all together:
data:text/html;charset=utf-8,
<html><title >Heuristic History Hysterics scURIple</title>
<!--
http://stackoverflow.com/questions/13369829/access-my-entire-browsing-history-via-javascript
/22773361# 22773361 -->
<!--
- scURIples (scriples) are generic schema (data:, javascript:, place:, ... ) URI that embed script
- data: scURIples (scriples) are amenable to direct cut & paste URI address bar evaluation
- generally no particular distinction is made between scURIples of different schema,
such as this data: schema URI, but ...
- javascript: schema specific scURIples are called scriplets or bookmarklets -->
<!--
a bookmark of this data: scURIple or its internal javascript: scriplet does the same thing -->
<!--
a place[s]: schema URI "works" from a bookmark only and not the address bar or a hyperlink -->
<!-- for internal use only (by the scURIbbler used to edit this script):
javascript: with ( opener . document . forms[0] . JS ) value =
value . replace( /\t|\n/g, function(c){ return escape(c) + c } ) ; close();//
scURIples are unscURIpulous
NB. no raw tabs, % 09 's collapse to null, quote raw %'s w/ non-numerics, };'s , ... -->
<script>
javascript:
String.prototype.HTMLtagWrap =
function ( tag, attrs) {
return tag[0]=="/" ?
"<" +tag+ ">" +this+ "<" +tag.substr(1)+ (attrs?" "+attrs:"") + ">" :
"<" +tag+ (attrs?" "+attrs:"") + ">" +this+ "</" +tag+ ">"
} ;
String.prototype.HTMLwrapTags =
function ( tagRA, atRA) {
return tagRA[0] ? this . HTMLtagWrap( tagRA.pop(), atRA.pop()) . HTMLwrapTags( tagRA, atRA)
: this
} ;
/* alert */ ( str =
( function(x){return x.HTMLtagWrap('title') + x.HTMLwrapTags(['/pre','center','b'] , [ ] ) }
('Heuristic History Hysterics')+
'1. '.HTMLtagWrap('b') +
'<input id=URIplcQry type=text size=120 ' +
'value="place:queryType=0&sort=8&maxResults=25" >\n' +
'suggestions:\t try just a raw place: with no corpus or places: (undocumented with an s)\n' +
'auto attribution:\t' +
'<input type=button onclick=URIplcQry.value+="&"+this.value value=sort=4 > \t' +
'<input type=button onclick=URIplcQry.value+="&"+this.value value=type=5 > \t' +
'<input type=button onclick=URIplcQry.value+="&"+this.value value=queryType=1 >\t ' +
'<input type=button onclick=URIplcQry.value+="&"+this.value value=domain="" >\t ' +
'<input type=button onclick=URIplcQry.value+="&"+this.value value=includeHidden=true >\t ' +
'<input type=button onclick=URIplcQry.value+="&"+this.value value=onlyBookmarked=true >\t' +
'\n\n2. '.HTMLtagWrap('b') +
'This link bookmarks the place: URI from step 1: ' +
'place: query URI href results' .
HTMLtagWrap( 'A',
' href="places:" rel="sidebar" title="hystryx " id="hystryx " ' +
' onmouseover ="with(this)title=id+(href=document.forms[0].URIplcQry.value)" '
) +
'\t(hint: to see the actual link, mouse over it 2x)' +
'\n\n3. '.HTMLtagWrap('b', ' style="vertical-align:top;" ' ) +
( '\n\t\t\tINSTRUCTIONS\n\n' +
'1. make the href place: query for the link in step 2. \n' +
'2. click the link to create a bookmark that accesses the URI library\n' +
'3. drag & drop the new bookmark (aka a container) here (replace this content)\n' +
'4. cleanup and delete the new bookmark if desired\n' +
'5. to be done: add a scURIbbler to massage this textarea\n' +
'\n\n' +
'tested with userAgent:\t\t\t\t' +
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4' +
'(Splashtop-v1.2.17.0) \n' +
'\twindow.navigator.userAgent =\t\t' + window.navigator.userAgent +
'\n '
) .HTMLtagWrap('textarea', 'id=histURIs rows=12 cols=120 nowrap') +
'\n\n4. ...'.HTMLtagWrap('b') +
'\n\n5. '.HTMLtagWrap('b') +
'scURIbbler: <input type=text size=120 id=histURIpg ' +
' value="javascript:with(opener)with(document.forms[0]) ' +
' ( URIplcQry.value.HTMLtagWrap(\'b\') + ' +
' histURIs.value.replace(/^.*$/g,function(m){return m.link(m)}) ' +
' ).HTMLwrapTags( \'html pre\'.split(/ +/) , [ ] ) ' +
' "><input type=button value="open histURIs" onclick=window.open(histURIpg.value )> ' +
' '
) . HTMLwrapTags ( ["html", "form", "pre"] , [ ] )
);
/*
window.open ( "data:text/html;charset=utf-8," + str . replace ( /\n/g, '%'+'0A ' ) );
*/
document.write ( str );
</script>
</html>

history.pushState how can I get rid of get parameters?

I am using
history.pushState('id','myTitle','myURL');
to manipulate the displayed URL and the history stack.
At some point I am pushing get parameters like so:
history.pushState('id','myTitle','?mySubLinkedStuff=hotSubLinkedStuff');
Now when I do
history.pushState('id','myTitle','#justSomeHashtag');
it produces http://example.com?mySubLinkedStuff=hotSubLinkedStuff#justSomeHashtag
I can also overwrite the value of mySubLinkedStuff but not seem to be able to get rif of it alltogether.
Desired result:
http://example.com#justSomeHashtag or http://example.com/#justSomeHashtag
and obviously I don't want to make the whole roundtrip over the server and I also want to avoid using absolute path or URL to keep the project portable.
As NimrodArgov rightly remarked: overwriting existing get-parameter strings works if you
push the full URL.
So for ensuring portability of the app (keep it usable on various domains) I did this:
history.statePush(document.location.origin + window.location.pathname + '#myHashValue');
Works perfectly well and fast.
To push current address without GET parameters :
history.pushState("id", "myTitle",
location.protocol + "//" + location.host +
location.pathname + location.hash
);
Other than that ;
To push a hash change I could do :
history.pushState("id", "myTitle",
location.protocol + "//" + location.host +
location.pathname + location.search + "#myHashHere"
);
To push a query change I could do :
history.pushState("id", "myTitle",
location.protocol + "//" + location.host +
location.pathname + "?my=query&over=here" + location.hash
);
※ Sorry I don’t have enough karma to just comment on Max’s answer… :/

Categories