Getting "appcontent" location.host - javascript

I am not an expert JavaScript user and I am having difficulty with addEventListener.
var appcontent = document.getElementById("appcontent");
appcontent.addEventListener("DOMContentLoaded", load, true);
function load(aEvent) {
var doc = aEvent.originalTarget;
alert(doc.location.host);
}
In an add-on this code will alert the location.host of the appcontent. My problem is that I don't need an event listener and want to call load like a normal function:
var appcontent = document.getElementById("appcontent");
load(appcontent);
function load(aEvent) {
var doc = aEvent.originalTarget;
alert(doc.location.host);
}
This is what I was trying to do but it doesn't work.

Your load() function still expects an event but you are now passing the actual element to it. Also, which location do you want to know, that of the currently selected tab? Then you can use the global content variable, it is pointing to the window object of the current tab. So changing the load() function into something like this should work:
function load() {
alert(content.location.host);
}
Use Ctrl+Shift+J to open JavaScript Console and to check the errors for your extension - it should help you find our what the issue is.

Related

How to invoke javascript function when # is present in URL

I am trying to call JavaScript function when # is present in URL. I know normal behavior is to navigate / scroll to the specific tag. But could not find how to invoke a JavaScript function.
The below example is close but not solving my problem.
What is the meaning of # in URL and how can I use that?
You might be able to leverage the hashchange event to trigger the function, assuming you don't just want to keep polling the location to see if it changes.
DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event
This code snippet will add the listener to the current page, then manipulate the hash and fire the function, displaying the new hash value. You could call any function here.
window.addEventListener('hashchange', function() {
alert(location.hash);
});
window.location += "#test";
var hash = window.location.hash;
if(hash){
// do something
}
<script>
if (window.location.href.includes('#')) {
// run your code here
}
</script>
use a location.hash function will solve your problem
var hash = window.location.hash.replace(/#/g, '');
if(hash){
// found a hash
console.log("heyy I found a hash")'
}
else{
// did not find a hash
console.log("Uh oh")
/*
try using :
window.location = window.location + '#' + "some random variable"
to create a new URL and every time the page loads find the hash and
display the wanted data.
*/
}
PS: this only works if your URL is like example.com/#xyz
then it will give you xyz as a console output. This may sound
vague but if you do this you may get a Idea

How can I run a script in another (newly-opened) tab?

I am trying to run a script in a new tab. The code I use is this:
$ = jQuery;
function openAndPush(url, id) {
var win = window.open('https://example.com' + url + '?view=map');
var element = $('<script type="text/javascript">console.log("Starting magic...");var region_id='+id+';$=jQuery;var p=$(\'div["se:map:paths"]\').attr(\'se:map:paths\');if(p){console.log("Found! pushing..."); $.get(\'https://localhost:9443/addPolygon\', {id: region_id, polygon: p}, function(){console.log("Done!")})}else{console.log("Not found!");}</script>').get(0);
setTimeout(function(){ win.document.body.appendChild(element);
console.log('New script appended!') }, 10000);
}
Considering the following:
I was inspired in this answer, but used jQuery instead.
I run this code in an inspector/console, from another page in https://example.com (yes, the actual domain is not example.com - but the target url is always in the same domain with respect to the original tab) to avoid CORS errors.
When I run the function (say, openAndPush('/target', 1)) and then inspect the code in another inspector, one for the new window, the console message Starting magic... is not shown (I wait the 10 seconds and perhaps more). However the new DOM element (this script I am creating) is shown in the Elements tab (and, in the first console/inspector, I can see the New script appended! message).
(In both cases jQuery is present, but not occupying the $ identifier, which seems to be undefined - so I manually occupy it)
What I conclude is that my script is not being executed in the new window.
What am I missing? How can I ensure the code is being executed?
Instead of embedding script element in the document, do this.
wrap the code that you want to run in another tab, into a function.
bind that wrapped function to the new tab's window
Call that function
Here's the code that I ran in my console and it worked for me i.e another tab was opened and alert was displayed.
function openAndPush(url, id) {
var win = window.open('https://www.google.com');
win.test = function () {
win.alert("Starting magic...");
}
win.test();
setTimeout(function () {
win.document.body.appendChild(element);
console.log('New script appended!')
}, 10000);
}
Found that my error consisted on the origin document being referenced when creating a new script node, instead of the target document (i.e. win.document). What I needed is to change the code to reference the new document and create the node directly, no jQuery in the middle at that point. So I changed my code like this:
function openAndPush(url, id) {
var win = window.open('https://streeteasy.com' + url + '?view=map');
var element = win.document.createElement('script');
element.type='text/javascript';
element.innerHTML = 'console.log("Starting magic...");var region_id='+id+';$=jQuery;var p=$(\'div[se\\\\:map\\\\:paths]\').attr(\'se:map:paths\');if(p){console.log("Found! pushing..."); $.get(\'https://localhost:9443/addPolygon\', {id: region_id, polygon: p}, function(){console.log("Done!")})}else{console.log("Not found! searched in: ", document);}'
setTimeout(function(){ win.document.body.appendChild(element); console.log('New script appended!') }, 10000);
}
With this code something is essentially happening: The JS code is being parsed (and its node created) in the context of the new document. Older alternatives involved the origin console (since the origin document was implicitly referenced).
It's bad practice to send scripts to another webpage. You can pass some query params using a complicated URL and handle it by a source code from another webpage, it's much better:
function doMagicAtUrlByRegionId (url, regionId) {
window.open(`https://example.com${url}?view=map&magic=true&region_id=${regionId}`);
}

Detecting when popup window is closed in Firefox

I open a new window like this:
var newWindow = window.open('myPage.aspx', null, 'height=650,width=900,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=0, left=0');
And I wait for it to close:
var windowTimer = window.setInterval(function () {
if (win.closed !== false) {
//If window is closed ...
window.clearInterval(windowTimer);
}
}, 100);
This does work in Chrome and IE9 and Edge but not in Firefox, why?
Firefox does get inside the function but it never gets on win.closed if, even if there is an else it neither goes into it... is there any alternative to this?
Solution that worked for me:
On the popup window:
//Fires an event on the window that opened it
window.onbeforeunload = function () {
window.opener.myEvent();
};
On the main window:
window.myEvent= function () {
//This fires only when the popup gets closed on beforeunload
}
Note: the event to fire in the main window must be declared as public so it can be accessible, like so window.myEvent= function ()
Another reference: cross-window javascript events
Basically, I think the simplest way to do this is the following:
function hasClosed(){
document.getElementById('open').textContent = 'window has been closed';
}
window.addEventListener('beforeunload', function(){
if(window.opener) window.opener.hasClosed();
});
document.getElementById('open').addEventListener('click', function(e){
e.preventDefault();
window.open('test.html');
});
open window
Please keep in mind that SO snippets are not allowed to open windows, so the code is not functional inside the snippet. Simply copy the code and save it as a file called test.html.
You do not need to keep checking, the child will simply call the function on the parent. This has the advantage that you are not using resources to keep checking for it. Also, be aware that when navigating in this window, onbeforeunload gets called if a new page is loaded, calling the parent function, but maybe you could just do the check you were already doing in the hasClosed function.
You might want to give an uuid to your window and pass it into it so it can inform you of it's identity on closing, but that's all refinement.

Access element in recently loaded XUL document

I'm developing a Firefox extension and need to do the following:
load a page
get an element from this page
modify the attributes from this element
The code I would like to work looks like this:
gBrowser.loadURI("chrome://myExtension/content/myPage.xul");
let button = content.document.getElementById("myExtension-theButton");
button.setAttribute("oncommand", "myFunction(withParams)");
But when I run this, button is null. (Maybe loadURI returns too early and the document isn't fully loaded, yet.)
add to that gBrowser:
gBrowser.addEventListener('DOMContentLoaded', dofunc, false);
function dofunc(e) {
var win = event.originalTarget.defaultView;
var doc = win.document;
if (doc.location == 'chrome://myExtension/content/myPage.xul') {
let button = content.document.getElementById("myExtension-theButton");
button.setAttribute("oncommand", "myFunction(withParams)");
gBrowser.removeEventListener('DOMCOntentLoaded', dofunc, false);
}
}

Writing html to a new window with javascript

I have been doing some research on opening a new window and writting HTML to it with jQuery/JavaScript and it seems like the proper way to do it is to:
Create a variable for the new window
var w = window.open();
Insert the new data and work the variable
$(w.document.body).html(data);
And to me, that makes complete sense. however when i try to incorporate this into my script ("data" being the holder for the HTML) it does not open a new window... unless I'm just missing something simple which as far as I can tell it looks great...
function newmore(str) {
var identifier = 4;
//get the history
$.post("ajaxQuery.php", {
identifier : identifier,
vanid : str
},
//ajax query
function(data) {
//response is here
var w = window.open();
$(w.document.body).html(data);
});//end ajax
}
Any ideas?
P.S. there seems to be no errors in the console
Your new window is probably being blocked by the popup blocker built into most browsers. If you create the new window as a direct result of a user action (key, click), then the browser usually will not block it. But, if you wait until sometime later (like after an ajax call completes), then it will get blocked and that is probably what is happening in your case.
So, the fix is usually to create the window immediately in direct response to the user event (don't wait until the ajax call completes), keep the window handle in a variable and then put the content in the window later after your ajax call completes.
function newmore(str){
var identifier = 4;
// create window immediately so it won't be blocked by popup blocker
var w = window.open();
//get the history
$.post("ajaxQuery.php", {
identifier : identifier,
vanid : str
},
//ajax query
function(data) {
//response is here
$(w.document.body).html(data);
});//end ajax
}
Try instead:
var w = window.open();
w.document.write(data);
The "innerHTML" property of the document object (which is what jQuery's .html() uses) represents the HTML document, which a new window doesn't have. Even if it did, putting a complete document inside an HTML document doesn't really make sense. It's a freshly-created document, so you can just write to it.
This peace of code will work:
var data = "<h1>Test</h1>";
var w = window.open("", "mywindow1", "width=350,height=150");
$(w.document.body).html(data);
You have to inform some parameters when opening new windows.
But, if possible, I'd hardly recommend that you use another way like, jquery UI or Twitter Bootstrap for doing that, so you will not be using pop-ups.

Categories