Razor CSS file location as Variable - html

I am wrapping a razor view in an iframe. The razor view is a web service on a different domain.
Here is what I am doing:
<!DOCTYPE html>
<html>
<body>
<p align="center">
<img src="http://somewhere.com/images/double2.jpg" />
</p>
<p align="center">
<iframe src="https://secure.somewhereelse.com/MyPortal?CorpID=12334D-4C12-450D-ACB1-7372B9D17C22" width="550" height="600" style="float:middle">
<p>Your browser does not support iframes.</p>
</iframe>
</p>
</body>
</html>
This is the header of the src site:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/themes/cupertino/jquery-ui-1.8.21.custom.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
</head>
I want the iframe src to use the CSS of the calling site.
Is there a way to pass in the CSS URL or have it inherit the CSS of the calling site?
I'd even settle for the css file location being a parameter being passed in from the originating site.
Anyone have any suggestions?

You cannot enforce your css on your site using an iframe. The css must be included in the source of the page included in an iframe. It used to be possible but in certain cases using javascript, and for the page to be on the same domain.
The only other way you may be able to use your own css is if the web service allows you to pass in the url of the css. But you would have to consult the documentation of the web service to find that out.

I would pass the CSS url as an argument to the iframe's src attribute:
<iframe src="http://somedomain.com/?styleUrl=#(ResolveStyleUrl())"></iframe>
Where ResolveStyleUrl might be defined as:
#functions {
public IHtmlString ResolveStyleUrl()
{
string url = Url.Content("~/Content/site.css");
string host = "http" + (Request.IsSecureConnection ? "s" : "") + "//" + Request.Url.Host + url;
return Raw(url);
}
}
This is of course assuming that the domain would accept a style url query string and render the appropriate <link /> on the remote page?

Eroc, I am sorry you cannot enforce your css on others' site using an iframe because most browsers will give an error like the one chrome gives:
Unsafe JavaScript attempt to access frame with URL http://terenceford.com/catalog/index.php? from frame with URL http://www.example.com/example.php. Domains, protocols and ports must match.
But this does not mean that you cannot extract the html from that page (which may be modified as per your ease)
http://php.net/manual/en/book.curl.php can be used for site scrapping with http://simplehtmldom.sourceforge.net/
First play with these functions:
curl_init();
curl_setopt();
curl_exec();
curl_close();
and then parse the html.
After trying yourself, you can look at this example below that I made for parsing beemp3 content, when I wanted to create a rich tool for directly downloading songs, unfortunately I couldn't because of the captcha but it is useful for you
directory structure
C:\wamp\www\try
-- simple_html_dom.php
-- try.php
try.php:
<?php
/*integrate results for dif websites seperately*/
require_once('simple_html_dom.php');
$q='eminem';
$mp3sites=array('http://www.beemp3.com/');
$ch=curl_init("{$mp3sites[0]}index.php?q={$q}&st=all");
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$result=curl_exec($ch);
curl_close($ch);
$html=str_get_html("{$result}");
$ret = $html->find("a");
echo "<head><style type='text/css'>a:link,a{font-size:16px;font-weight:bold;font-family:helvetica;text-decoration:none;color:#458;}a:hover{color:#67b;text-decoration:underline;}a:visited{color:silver;}</style></head>";
$unik=array(null);
foreach($ret as $link)
{
$find="/(.{1,})(\.php)[?](file=.{1,})&song=(.{1,})/i";
$replace="$4";
if(preg_match("{$find}",$link->href))
{
$unik[]=$link->href;
if(current($unik)===prev($unik)){unset($unik);}
else{
echo "<a href='".$mp3sites[0].$link->href."'>".urldecode(preg_replace($find,$replace,$mp3sites[0].$link->href))."</a><br/>";
}}
}
?>
I know that you do not code in php, but I think you are capable of translating the code. Look at this:
php to C# converter
I spent time on this question because only I can understand what it means to offer bounty.
May be the answer seems unrelated (because I have not used javascript or html based solution), but because of cross-domain issues this is an important lesson for you. I hope that you find similar libraries in c#. Best of luck

The only way I know to achieve that is to make the HTTP request on your server side, fetch the result and hand it back to the user.
A minima, you'll need either to strip completely the header from the targeted site to inject the content in your page using AJAX, or to inject your own css in the page headers to put it into an IFRAME.
Either way you have to implement the proxy method, which will take the targetted URL as an argument.
This technique has many downsides :
You have to do the queries on you server, which can cost a lot of bandwidth and CPU
You have to implement the proxy
You cannot transmit the domain specific cookies from the user, though you can manage new cookies have by rewriting them
If you do a lot of requests you server(s) is/are likely to become blacklisted on the targeted website(s)
The benefits sound low compared to the hassles.

Related

iFrame is not displaying website (cross-site request error)

I have been on an adventure to get a sportsbook dashboard in my mancave. With the main goal to display the lines of my Prefered sportsbook. Based on some googling and digging all the API's cost money. I settled on using the Game Center by Pregame, which I use quite often anyways.
So they have embed code for the GameCenter and I have a fairly basic HTML page going but somethings not quite right and it's displaying all wonky. I can't tell if it's my code or Pregame that is the issue. Any help or guidance would be appreciated.
Link to the Static Page: https://dashboard.megustasports.com/Untitled-1.html
Pregame Gamecenter: https://pregame.com/game-center
EDIT
Here are the errors from the Chrome console
Indicate whether to send a cookie in a cross-site request by
specifying its SameSite attribute Because a cookie's SameSite
attribute was not set or is invalid, it defaults to SameSite=Lax,
which prevents the cookie from being sent in a cross-site request.
This behavior protects user data from accidentally leaking to third
parties and cross-site request forgery.
Resolve this issue by updating the attributes of the cookie: Specify
SameSite=None and Secure if the cookie should be sent in cross-site
requests. This enables third-party use. Specify SameSite=Strict or
SameSite=Lax if the cookie should not be sent in cross-site requests
9 cookies Name Domain & Path .te.dpr pregame.com/
_ga .pregame.com/
_gid .pregame.com/ .te.w pregame.com/ Telligent.Evolution-UI pregame.com/ tzoffset pregame.com/
tzid pregame.com/ .te.dpr pregame.com/utility
.te.w pregame.com/utility 2 requests pg.authentication.js
error-notfound.aspx?item=%2fassets%2fscripts%2fpg.…entication&user=extranet%5cAnonymous&site=website
Here is the HTML I am currently using:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Here the title</title>
<style>
*{
margin: 0px;
}
iframe {
display: block !important;
width: 100%;
height: 100vh;
}
</style>
</head>
<body>
<script src="https://pregame.com/assets/scripts/tear/tear.js" data-type="generic" data-url="https://pregame.com/game-center?ts_i=game-center"></script>
</body>
</html>
In theory, the end result should only contain the table from the page linked above and look something similar to this:
Instead of using an iframe, try making a HTTP request and storing that in a div:
var cors_api_url = 'https://cors-anywhere.herokuapp.com/';
function doCORSRequest(options, printResult) {
var x = new XMLHttpRequest();
x.open(options.method, cors_api_url + options.url);
x.onload = x.onerror = function() {
printResult(
(x.responseText || '')
);
};
if (/^POST/i.test(options.method)) {
x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
x.send(options.data);
}
doCORSRequest({
method: 'GET',
url: 'https://pregame.com/game-center/',
data: ''
}, function printResult(result) {
document.querySelector('.result').innerHTML = result;
});
<div class="result"></div>
Problem
CORS is designed to prevent malicious websites from imitating a legitimate one. The Pregame Game Center’s CORS policy requires that the website embedding an iframe containing their website be on the same domain. To use an iframe from your domain, the Pregame Game Center developers would have to add your domain to their CORS policy.
Solution
Consider instead programmatically navigating their website and pulling information you need from it (scraping), then creating your own website to display that information. This is the most roundabout way, but generally accepted if there is no API you can use to access the information you need. Through investigation you may even come across a JSON formatted endpoint used by their front end to retrieve information to be displayed (their private API) that you can use.
Note
Scraping and republishing information produced by Pregame Game Center may be against their terms and conditions. You may be able to avoid legal implications if you host the website locally, or remotely behind authentication.
References
CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Web scraping (Python - Beautiful Soup) Tutorial: https://realpython.com/beautiful-soup-web-scraper-python
Django (Python web framework): https://www.djangoproject.com
You cannot use iframe to display some of the websites like Google.
This is a security measure implemented to protect their website and customer data from being attacked.
If you want to get some details of the website, you can use their API if they provide.
That is the best option.
You can search for a bunch of API's available on the web for your requirement.

Angular 9 domSanitazer Not allowed to load resource [duplicate]

It works if the html file is local (on my C drive), but not if the html file is on a server and the image file is local. Why is that?
Any possible workarounds?
It would be a security vulnerability if the client could request local file system files and then use JavaScript to figure out what's in them.
The only way around this is to build an extension in a browser. Firefox extensions and IE extensions can access local resources. Chrome is much more restrictive.
shouldn't you use "file://C:/localfile.jpg" instead of "C:/localfile.jpg"?
Browsers aren't allowed to access the local file system unless you're accessing a local html page. You have to upload the image somewhere. If it's in the same directory as the html file, then you can use <img src="localfile.jpg"/>
C: is not a recognized URI scheme. Try file://c|/... instead.
Honestly the easiest way was to add file hosting to the server.
Open IIS
Add a Virtual Directory under Default Web Site
virtual path will be what you want to browse to in the browser. So if you choose "serverName/images you will be able to browse to it by going to http://serverName/images
Then add the physical path on the C: drive
Add the appropriate permissions to the folder on the C: drive for "NETWORK SERVICE" and "IIS AppPool\DefaultAppPool"
Refresh Default Web Site
And you're done. You can now browse to any image in that folder by navigating to http://yourServerName/whateverYourFolderNameIs/yourImage.jpg and use that url in your img src
Hope this helps someone
we can use javascript's FileReader() and it's readAsDataURL(fileContent) function to show local drive/folder file.
Bind change event to image then call javascript's showpreview function.
Try this -
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;'>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function showpreview(e) {
var reader = new FileReader();
reader.onload = function (e) {
$("#previewImage").attr("src", e.target.result);
}
//Imagepath.files[0] is blob type
reader.readAsDataURL(e.files[0]);
}
</script>
</head>
<body >
<div>
<input type="file" name="fileupload" value="fileupload" id="fileupload" onchange='showpreview(this)'>
</div>
<div>
</div>
<div>
<img width="50%" id="previewImage">
</div>
</body>
</html>
IE 9 : If you want that the user takes a look at image before he posts it to the server :
The user should ADD the website to "trusted Website list".
Newtang's observation about the security rules aside, how are you going to know that anyone who views your page will have the correct images at c:\localfile.jpg? You can't. Even if you think you can, you can't. It presupposes a windows environment, for one thing.
if you use Google chrome browser you can use like this
<img src="E://bulbpro/pic_bulboff.gif" width="150px" height="200px">
But if you use Mozila Firefox the you need to add "file " ex.
<img src="file:E://bulbpro/pic_bulboff.gif" width="150px" height="200px">
starts with file:/// and ends with filename should work:
<img src="file:///C:/Users/91860/Desktop/snow.jpg" alt="Snow" style="width:100%;">
I see two possibilities for what you are trying to do:
You want your webpage, running on a server, to find the file on the computer that you originally designed it?
You want it to fetch it from the pc that is viewing at the page?
Option 1 just doesn't make sense :)
Option 2 would be a security hole, the browser prohibits a web page (served from the web) from loading content on the viewer's machine.
Kyle Hudson told you what you need to do, but that is so basic that I find it hard to believe this is all you want to do.
If you're deploying a local website just for yourself or certain clients, you can get around this by running mklink /D MyImages "C:/MyImages" in the website root directory as an admin in cmd. Then in the html, do <img src="MyImages/whatever.jpg"> and the symbolic link established by mklink will connect the relative src link with the link on your C drive. It solved this issue for me, so it may help others who come to this question.
(Obviously this won't work for public websites since you can't run cmd commands on people's computers easily)
I have tried a lot of techniques and finally found one in C# side and JS Side.
You cannot give a physical path to src attribute but you can give the base64 string as a src to Img tag.
Lets look into the below C# code example.
<asp:Image ID="imgEvid" src="#" runat="server" Height="99px"/>
C# code
if (File.Exists(filepath)
{
byte[] imageArray = System.IO.File.ReadAllBytes(filepath);
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
var val = $"data: image/png; base64,{base64ImageRepresentation}";
imgEvid.Attributes.Add("src", val);
}
Hope this will help
background-image: url(${localImage});
If you want to add a file as background to your website locally.
You need to upload the image aswell, then link to the image on the server.
what about having the image be something selected by the user? Use a input:file tag and then after they select the image, show it on the clientside webpage? That is doable for most things. Right now i am trying to get it working for IE, but as with all microsoft products, it is a cluster fork().

Call one html file from another

I want to call one html page fron another in a div.
I tried using
<include file="NavigationTree.html" />
and
<? include("/starfix/pages/NavigationTree.html"); ?>
But it doesn't work.
Am I doing something wrong or do i need to do it some other way?
You may want to consider using Server Side Includes (SSI).
You would place your HTML snippet into a separate file, such as NavigationTree.html, and then you would simply reference it in your web pages by using:
<!--#include virtual="NavigationTree.html" -->
SSI is supported by all the popular web servers, including Apache, IIS and lighttpd.
Note that if you are using a shared host, you may have to use the .shtml, .stm, or .shtm extension for SSI to work. If you have root access to your web server, it can be easily configured to enable SSI for any extension, including html.
This is not possible in pure HTML.
The former is a notation I have never seen before, it is not HTML, maybe it works in some specific server-side templating language.
The latter is PHP. It should work but you need to bear in mind include() works with absolute paths inside the server's file system.
You should specify a relative path:
<? include("./NavigationTree.html"); // will work if it's in the same directory ?>
or an absolute one that will probably look something like this:
<? include("/path/to/your/www/dir/starfix/pages/NavigationTree.html"); ?>
(ask your admin for the absolute path to your web root)
You can maybe also do a HTTP include:
but that's unwise because it tends to be slow, and generates a second request on each page request.
You can also use SSI as outlined by #Daniel.
You could also use jQuery for this,
e.g.
<div id="yourDiv" />
<script>
$("#yourDiv").load("NameOfYourPageToReadFrom.ext #NameOfDivToReadFrom");
</script>
This puts the contents of the 'NameOfDivToReadFrom' DIV in the called file ''NameOfYourPageToReadFrom' into the loaded DIV ('yourDiv') in your current file.
Remember to add the definition to the header part of your html.
e.g.
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
You can use an iframe for that, e.g.:
<iframe width="500" height="300" frameborder="no" scrolling="no" marginheight="0" marginwidth="0"
src="http://www.example.com/page.html"></iframe>

Embedding part of a web site

Suppose I want to embed the latest comic strip of one of my favorite webcomics into my site as a kind of promotion for it. The webcomic has the strip inside of a div with an id, so I figured I can just embed the div in my site, except that I couldn't find any code examples for how to do it (they all show how to embed flash or a whole website).
Can someone please show me (or tell) how it's done?
PS I'd rather not use server side scripting or external services (which is what is often recommended for embedding RSS).
Update - Cross domain request with jQuery (on client side)
Yesterday I was browsing James Padolsey's blog, where he posted a great article, on how to do cross domain request with jQuery, also Chris Heilmann has a nice DEMO.
The principle is to use YQL -> a yahoo api for web page queries, where you receive a JSON with all the html. Happy scraping :)
Scrape remote data with php, load with jQuery
What about considering simple AJAX call, that would intercept the comic element and update with its contents your <div id="update-comic" /> primarily used for this purpose?
Also you will use a simple php to get the remote page, cause you cannot make ajax call on another domain
note: user must have JavaScript enabled, also following code uses jQuery library
Putting it all together
on your page, where you want to display remote comic strip create a div only for this purpose, lets call it update-comic
<div id="update-comic">
<!-- here comes scraped content -->
</div>
write down the php, call it comic-scrape.php, it will download the html from remote page, you should consider caching the response and updating it on a specified interval (e.g. 30min, 1hr, your call.. :))
server performance should not suffer after simple cache checking implementation
<?php
$url = 'http://www.example.com/';
$response = file_get_contents($url);
echo $response;
now comes the jQuery magic, where you make ajax call on your php scraper and take only the relevant element you are interested in. Place this script inside your view page (where you have your <div id="update-comic" />
<script type="text/javascript">
$(function () {
// set all your required variables
var
localUrl = '/comic-scrape.php',
elementId = '#remote-comic-id',
elementToUpdate = $('#update-comic');
// update the local elementToUpdate with elementId contents
// from your php in localUrl
elementToUpdate.load(localUrl + ' ' + elementId;
});
</script>
I hope, I covered everything.
Employing simplexml and xpath
As philfreo suggested in comment, a viable solution could also contain selecting the required id server-side. It is very easy with use of php's simplexml and a little xpath:
<?php
// set remote url and div id to be found
$elementId = 'remote-comic-id';
$url = 'http://www.example.com/';
// instantiate simple xml element and populate from $url
$xml = new SimpleXMLElement($url, null, true);
// find required div by id
$result = $xml->xpath("//div[id={$elementId}]");
// take first element from array, which is our desired div
$div = array_pop($result);
echo $div;
It's impossible because you cannot manipulate iframe/frame content. Using iframe tag will just modify content in tag, but not the src.
Neither with AJAX, because you have to be on the same domain.
So, for example, you can use PHP with cURL or quite simply with fopen.
You can just use an iframe. The content isn't literally on that page, but it looks like it.
Here's an example: http://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_iframe
It looks like this:
<iframe src ="http://www.example.com/index.html" width="100%" height="300"></iframe>
<embed src="url of your comic" width="300" height="250" />

How can I use templates to generate static web pages?

I want to add one HTML file into another.
For example: I have header.html and footer.html
Now I am trying to create aboutus.html where I want to add these two HTML files
there is no dynamic code in these file except JavaScript.
How can I do this without using any scripting language except JavaScript and CSS?
Server Side Includes (SSI) exist for this particular functionality. However, you need to have the server configured for such includes. Apache supports it. Not sure about other web servers.
or Server Side Includes (SSI), all embedding is done there on the server side...
In the case of web sites with no dynamic content but have common elements, I generate the final pages on my development machine using Perl's Template Toolkit and upload the resulting static HTML files to the server. Works beautifully.
For example:
header.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<title>[% title %]</title>
<link rel="stylesheet" href="/site.css" type="text/css">
<meta name="description" content="[% description %]">
<meta name="keywords" content="[% keywords.join(',') %]">
</head>
<body>
<div id="banner">
<p>Banner</p>
</div>
footer.html
<address>
Last update:
[%- USE date -%]
[%- date.format(date.now, '%Y-%m-%d %H:%M:%S') -%]
</address>
</body>
</html>
aboutus.html
[%- INCLUDE header.tt.html
title = 'About Us'
description = 'What we do, how we do it etc.'
keywords = 'rock, paper, scissors'
-%]
<h1>About us</h1>
<p>We are nice people.</p>
You can now use tpage or ttree to build your pages.
The only way to do this on the client side without javascript is to use frames or iframes. If you want to use javascript, you can use AJAX. Most javascript frameworks provide corresponding convenience methods (e.g. jQuery's load function).
Obviously there are many server side solutions, including the popular SSI extension for apache (see other posts).
I'm not entirely sure what it is you want but an entirely client side method of doing it would be to embed them with the <object> tag.
<html>
<head>
<title>About Us</title>
</head>
<body>
<object data="header.html"><!--Something to display if the object tag fails to work. Possibly an iFrame--></object>
<!--Content goes here...-->
<object data="footer.html"></object>
</body>
</html>
I do not think that this would work if either header.html or footer.html have javascript that accesses the parent document. Getting it to work the other way might be possible though.
Check out ppk's website (quirksmode.org), and go to the javascript archives,
(http://quirksmode.org/js/contents.html). He uses an ajax function he wrote called sendRequest (found at http://quirksmode.org/quirksmode.js). Since IE9+ plays nice with standards, I've simplified it some:
function sendRequest(url,callback,postData) {
var req = new XMLHttpRequest();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
req.setRequestHeader('User-Agent','XMLHTTP/1.0');
if (postData)
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
// alert('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
Then use the sendRequest function by wrapping the setFooter, setHeader functions and any other content functions around it.
why not use php or any other side scripting language?
doing this with javascript will not all users allow to watch your page.
Whilst this can be done with JS in a number of ways (AJAX, iframe insertion) it would be a very bad idea not to do this within the mark-up directly or (much) better on the server side.
A page reliant on JS for it's composition will not be fully rendered on a significant proportion of user's browsers, and equally importantly will not be correctly interpreted by google et al, if they like it at all.
You can do it, but please, please, don't.
Obviously header.html and footer.html are not html files -- with full fledged headers etc. If you have just html snippets and you want to include them so you can create different pages - like aboutus.html, terms.html, you have a couple of options:
Use a framework like Rails - which allows you to use layouts and partials. [** heavy **]
Write a simple tool that will generate all the files by concat-ing the appropriate files.
I assume you are doing this to avoid duplicating header and footer content.
Another way would be using ajax to include the remote html files.
Framesets would be the way to do this without any script or serverside influences.
<frameset rows="100,*,100">
<frame name="header" src="header.html" />
<frame name="content" src="content.html" />
<frame name="footer" src="footer.html" />
</frameset>
HTML5 framesets:http://www.w3schools.com/tags/html5_frameset.asp
This is a very dated solution, most web hosts will support server side includes or you could use php to include your files
http://php.net/manual/en/function.include.php
Cheers