Calling external HTML page inside Javascript - javascript

i am trying to call a external HTML page to be displayed on website based on javascript conditions.
The code is like this
<script language="JavaScript" src="http://j.maxmind.com/app/country.js"></script>
<script type="text/javascript">
var country = geoip_country_code();
if (country == "US")
{
document.write("http://www.mywebsite.com/1.html");
}
else if (country == "GB")
{
document.write("<a href='#'><img src='http://www.image2.com' ><a/>");
}
else
{
document.write("<a href='#'><img src='http://www.image3.com' ><a/>");
}
</script>
Now, instead of showing the content of HTML page to US visitors, it just display "http://www.mywebsite.com/1.html" as plain text.
I am missing a function to call external HTML. Can someone help? Thanks

Do you mean the <iframe> element?
document.write('<iframe src="http://www.mywebsite.com/1.html"></iframe>');
Since <iframe> cannot resize itself to match the size of its content, be sure to give it a width/height attribute or style (if you know the actual size of content).

Spitting the text of a URL into a page doesn't magically grab the contents of that page. This type of activity usually happens on the SERVER where your server will fetch the content from another page and serve it up as part of YOUR page. JavaScript is the wrong tool for this job.

this kind of thing is really better to do server-side with stuff like php but here's a function I use in a lot of my commercial jobs. Again, I don't condone the use of this function for loading entire pages, but it's a really handy one to have in your toolbox. If anyone says you have to use JQuery to do this, kick them for me. ^_^
function fetchHTML(url)
{
if( 'undefined' == typeof(url) ) return false;
if( document.all ){
p = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
p = new XMLHttpRequest();
}
rnd = Math.random().toString().substring(3);
if( url.indexOf('?') > -1 )
{
url+='&rnd='+rnd;
}
else
{
url+='?rnd='+rnd;
}
p.open("GET",url,false);
p.send(null);
return p.responseText;
}

well, you are giving a string to document.write() function, and that's why it is displaying the string that it was supposed to display. If you want to display content of some other page you have two choices either you can use an <iframe> or use ajax.

Related

Button not showing in Plone, onclick also not working

I am editing a plone page to open an Excel document on a specific sheet. I created two buttons to see if either would appear as actual buttons and use the JS function I reference. With this code the exact part of the page looks like the image below.
Why is only text showing instead of the button and why is the onclick attribute not working?
Note: I have changed to links to the spreadsheet for posting it on here but the link has been tested on other webpages
<script type="text/javascript">
function Open_Excel_File(path,sheet)
{
fso = new ActiveXObject("Scripting.FileSystemObject");
if (!fso.FileExists(path))
alert("Cannot open file.\nFile '" + path + "' doesn't exist.");
else
{
var myApp = new ActiveXObject("Excel.Application");
if (myApp != null)
{
myApp.visible = true;
Book = myApp.workbooks.open(path);
var excel_sheet = Book.Worksheets(sheet).Activate;
myApp.range(f_range).Select;
}
else {
alert ("Cannot open Excel application");
}
}
}
</script>
<div>
<button onclick='Open_Excel_File("file://///fs-01\Departments\Underwriting\Statistical%20Data%20and%20Medical%20Information\Statistics\Cancers\Cancer%20Statistics%\Cancer%20Statistics%.xlsx", "Vulvar Ca");'>Open File</button>
<input type="button" onclick="Open_Excel_File('file://///fs-01\deps\uw\stat%20Data%20and%20Medical%20Information\Statistics\Cancers\Cancer%20Statistics%202018\Cancer%20Statistics%.xlsx', 'VCA');'>OPEN FILE</input>
</div>
your onclick value is not a function, it is the result of a function call. Try to change that to onclick="Open_Excel_File"; You'll have to provide the file path at some point
Accessing file system from browser is super restricted for security matters, the only way I see fit is to have a file input and using what user provides
Also Plone filter out a bounce of potential "nasty" tags through a specific configurable tool.
It seems to me that you have injected the in the source HTML of a Page (document) type.
If so, you will see in your browser that in, the page source code, the script tag has been totally stripped away.
So,
a correct way to inject some js in your page, is to load it as portal_javascript resource (plone<=4) or in resource_registry (plone>=5).
tha nasty way is to access, in the ZMI, at https://yourseite:8080/Plone/portal_transforms/safe_html/ and configure it to accept script tags inside a document (all document in your site actually).
If this answer does not satisfy you try to ask in the official community:
http://community.plone.org
hth,
alessandro

JavaScript ignore missing DOM element/event

I am developing a new application where different pages has different DOM element like Map page has some map specific element and Message page has message specific. To reduce the number of requests, I am combining all scripts to one file and put into footer.
But the problem is that when I am on Map Page, getting error for the missing elements that are only exists on Message page, I believe I am missing something very easy but I could not figure it out.
You can use try and catch if you don't want your script stops.
i.e.
try{
var test = document.getElementById("someelementthatdontexsist");
alert(test.innerHTML);
}
catch(err){};
so as Esko suggested you need to use "if" to check if you are on right page to run appropriate code.
sample:
var PageName = document.getElementsByTagName('body');
document.getElementById("check_button").addEventListener('click', function () {
if (PageName[0].getAttribute('id') == "map_page") {
//do map_page things
document.getElementById("page_name").innerText = PageName[0].getAttribute('id');
}
if (PageName[0].getAttribute('id') == "message_page") {
//do message_page things
document.getElementById("page_name").innerText = PageName[0].getAttribute('id');
}
});
<body id="map_page">
<button id="check_button">Check page</button>
<span id="page_name">test
</span>
</body>

problems with javascript function loading content from other files

Basically I'm trying to build a functionality in which I only really edit my index.php, I got a lot of other php files with just a form in them or just a few lines of text.
What I want to achieve is to load these other files in the contentwrapper of my index.php.
I have been successfull on doing this with an iframe and with a html <object>.
The problem with these though is that first of all they load an all new #document in the DOM, and also my webpage has no set height so height: 100% won't work on those and I would get these ugly scrollbars and stuff.
after searching a lot on SO today I found a few interesting solutions which I combined, this is what I'm trying now:
<script type="text/javascript" href="js/csi.min.js"></script>
<script type="text/javascript">
function load_content(target){
document.getElementById('contentwrapper').innerHTML='<div data-include="' + target + '" ></div>';
return false;
}
</script>
now you may question what data-include is, this is a very nice workaround I found on SO.
THIS is what it does, it basically calls a .js file that replaces the containing element with the data that is in the file (target in the above example)
I call this functionality like this:
Update profile
It works as far as adding this to the DOM:
<div id="contentwrapper">
<div data-include="update.php" ></div>
</div>
but besides that it does nothing, I think that it doesn't call the .js file for the data-include attribute. But I can't find a solution for this nowhere.
(BTW: the data-include attribute does work if I put it in a tag manually without javascript)
I Hope I didn't overexplain the situation, and I thank everyone that tries to help in advance!
The csi.js script is only run once after the page is loaded. It just goes over all the elements with the data-include attribute and runs the fragment function.
<script type="text/javascript">
function fragment(el, url) {
var localTest = /^(?:file):/,
xmlhttp = new XMLHttpRequest(),
status = 0;
xmlhttp.onreadystatechange = function() {
/* if we are on a local protocol, and we have response text, we'll assume
* things were sucessful */
if (xmlhttp.readyState == 4) {
status = xmlhttp.status;
}
if (localTest.test(location.href) && xmlhttp.responseText) {
status = 200;
}
if (xmlhttp.readyState == 4 && status == 200) {
el.outerHTML = xmlhttp.responseText;
}
}
try {
xmlhttp.open("GET", url, true);
xmlhttp.send();
} catch(err) {
/* todo catch error */
}
}
function load_content(target){
fragment(document.getElementById('contentwrapper'), target);
return false;
}
</script>
Then call it like this:
Update profile
So, the only thing you need is to call this function for the new created element. Pass the DOM element and the url to this function and it will take care of loading the contents of the requested resource in the corresponding element.
May we assume that you followed this advise from the repository: The only caveat is Chrome, which restricts access to local files via AJAX. To resolve this, simply add --allow-file-access-from-files to your Chrome runtime.
If you didn't, and you're using Chrome, then this stands out to me, and you didn't indicate that you'd corrected the security block that Chrome puts in place.
The csi.js only runs on window.onload.
Try
<a href="#" onclick="function() {load_content('update.php'); window.onload(); }">
Update profile</a>

Google related bar - how to keep from showing up on my website

A new "google related" bar shows up at the bottom of my website. It displays links to my competitors and other things like maps, etc. It is tied in with users using the google toolbar. If anyone has any ideas on how I can disable from displaying on my web side I would sure appreciate it.
Taken from http://harrybailey.com/2011/08/hide-google-related-bar-on-your-website-with-css/
Google inserts an iframe into your html with the class .grelated-iframe
So hiding it is as simple as including the following css:
iframe.grelated-iframe {
display: none;
}
Google removed div and frame names and put everything to important so original answer no longer works on my site. We need to wait for the iframe to be created and then hide it by classname. Couldn't get .delay to work, but this does...today anyway.
$(document).ready(function() {
setTimeout(function(){
$(‘.notranslate’).hide();},1000);
});
Following javascript code tries to find the google related iframe as soon as the window finishes loading. If found, it is made hidden, else an interval of one second is initialized, which checks for the specified iframe and makes it hidden as soon as it is found on page.
$(window).load(function (){
var giframe = null;
var giframecnt = 0;
var giframetmr = -1;
giframe = $("body > iframe.notranslate")[0];
if(giframe != null)
$(giframe).css("display", "none");
else
giframetmr = setInterval(function(){
giframe = $("body > iframe.notranslate")[0];
if(giframe != null) {
clearInterval(giframetmr);
$(giframe).css("display", "none");
} else if(giframecnt >= 20)
clearInterval(giframetmr);
else
giframecnt++;
}, 1000);});
Find the parent DIV element that contains the stuff in the bar. If it has an id or name attribute, and you can control the page CSS then simply add a rule for the element, i.e. if you see something like
<div id="footer-bar-div".....
then add a CSS rule
#footer-bar-div {display:none ! important}
This will not work if the bar is inside an iframe element, but even in that case you should be able to hide it using javascript, but you will need to find the name/id of the frame, i.e.:
var badFrame = document.getElementById('badFrameId').contentWindow;
badFrame.getElementById('footer-bar-div').style.display='none';
if the frame has a name, then instead you should access it with:
var badFrame = window.frames['badFrameName']
There is also a chance that the bar is generated on-the-fly using javascript. If it is added to the end of the page you can simply add a <noscript> tag at the end of your content - this will prevent the javascript from executing. This is an old trick so it might not always work.

append element in head of an iframe using jquery

i want to append a style sheet(css) link to the head of an iframe using jquery .
i tried with the following code but not working.
$('#tabsFrame').contents().find("head").append(cssLink);
i am used to append data to an iframe by using this line of code
$('body', window.frames[target].document).append(data);
In your case, this line would look like this
$('head', window.frames['tabsFrame'].document).append(cssLink);
EDIT:
Add <head></head> to the iframe and change your var cssLink to
cssLink = '<link href="cupertino_1.4/css/cupertino/jquery-ui-1.8.7.custom.css" type="text/css" rel="Stylesheet" class="ui-theme" />
well, you can check with this:
$('#tabsFrame').contents().find("head")[0].appendChild(cssLink);
I believe you can't manipulate the content of an iframe because of security.
Having you be able to do such a thing would make cross-site-scripting too easy.
The iframe is totally seperate from the DOM of your page.
Also, java and javascript are two completely different things!
Follow the Link to see the difference here
This could be related to IE not allowing you to add elements in the DOM, check out the clever solution here
EDIT:
Thanks #kris, good advice to add more info in case links break:
Here is the main code snippet from the link, in case it goes out again.
(This is only needed with some IE version, for the most part, the other answer work just fine)
var ifrm;
//attempts to retrieve the IFrame document
function addElementToFrame(newStyle) {
if (typeof ifrm == "undefined") {
ifrm = document.getElementById('previewFrame');
if (ifrm.contentWindow) {
ifrm = ifrm.contentWindow;
} else {
if (ifrm.contentDocument.document) {
ifrm = ifrm.contentDocument.document;
} else {
ifrm = ifrm.contentDocument;
}
}
}
//Now that we have the document, look for an existing style tag
var tag = ifrm.document.getElementById("tempTag");
//if you need to replace the existing tag, we first need to remove it
if (typeof tag != "undefined" || tag != null) {
$("#tempTag", ifrm.document).remove();
}
//add a new style tag
$("HEAD", ifrm.document).append("");
}

Categories