How to get the document of an embedded website with JS? - javascript

Im trying around with HTML and found the -tag.
I provided an url as src and the website does load without problems.
However I canot get the HTML-Code of this inner website. How can I access it with JS?
I already tried innerHTML, children, childNodes etc.
HTML
<div class="Webframe">
<embed id="webframe" src="http://testapp.galenframework.com/"></embed>
</div>
Console output of
let webframe = document.getElementById("webframe");
console.log(webframe)
can be seen here
https://imgur.com/JH2jzKr
If anyone has an idea how to access this #document, I would be happy to try it out
Thank you in advance

Your first problem is the lack of interface to do your task with <embed>. Better to use <iframe>.
The second is to try to access content from another domain without CORS. (See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin)
Lets try a local page in a <iframe>. Now you can access the iframescontentDocument`:
<iframe id="webframe" src="test2.html"></iframe>
<script>
let webframe = document.getElementById("webframe");
webframe.onload = ()=> console.log(webframe.contentDocument.body.outerHTML);
</script>
If you have access to another domain server, you can add "Access-Control-Allow-Origin: *" to the HTTP header and try it.

<div class="Webframe">
<embed id="webframe" src="http://testapp.galenframework.com/" />
</div>
let webframe = document.getElementById("webframe");
console.log(webframe)

Related

Back and Forward Control for an iframe using pure JavaScript/JQuery

I need to create a tightly controlled environment for opening certain pages that need back and forward navigation controls. I had poked around on here and found this question and tried to implement it, but I'm having a problem.
I have the following for the HTML and Javascript going on, assume it's already styled (reusing code from previous project), and JQuery is already listed in the <head></head> tags:
<body>
<div id="header">
<div id="shortcutbar">
<a id="backBtn" onclick =="iframeBack();"></a>
<a id="forwardBtn" onclick =="iframeForward();"></a>
</div>
</div>
<div id="displayContainer">
<iframe id="display" src="https://website.goes.here/">
</iframe>
</div>
<script>
function iframeBack() {
$("#display").contentWindow.history.go(-1);
}
function iframeForward() {
$("#display").contentWindow.history.go(1);
}
</script>
</body>
Checking the console, I get the following error: Uncaught TypeError: Cannot read property "history" of undefined and it gives both whatever line the function is called in the HTML, and the line of the function itself in the script tags.
I'm at a loss of what isn't working, as everything I've found thus far just refers to some variation of what I've already typed.
The jQuery object doesn't have contentWindow property.
You need the underlying element ... $("#display")[0].contentWindow.
With that said if the iframe source is from a different origin than the main page you are security restricted from accessing the frame window using javascript
You can use postMessage also for secure communication
$("#display").contentWindow.postMessage('back');
window.addEventListener('message', ({ data }) => {
data === "back" && window.history.back()
});
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

How to correctly put URL into jQuery load()?

What I want to do is, from example.com/page1, to load text of an ID from homepage example.com into class class.
What I've tried:
$('.class').load('example.com #ID');
But what this does is try to load from example.com/page1/example.com instead of just example.com
I've also tried:
var urltoload = 'https://example.com/';
$('.class').load(urltoload, '#ID');
which does load content but loads the entire page! instead of just the content from the example.com ID.
Then there's also the fact that I still haven't guessed the syntax for getting just the text from that ID. Maybe something like $('.class').load(urltoload, $('#ID').text()); ?
Thank you for any help here.
this code works for me:
Html:
<div class="class"></div>
<input id="id" value="3"/>
Script:
$(".class").html('<object data="http://validator.w3.org?id="+$("#id").val()/>');
You can do like this:
GET:
$('.class').load("template.html?Id = VALUE_TO_PASS");
POST:
$('.class').load("template.html",{Id = VALUE_TO_PASS});

Find elements by attribute's partial value

I have some img tags inside iFrame(id=iframe1) on my page.
Some of them has src attribute set to myimg.jpg, 'myimg_small.jpg', myimg_large.jpg etc.
I am trying to find everything inside #iframe1 with src like myimg, so I wrote
images = $('#iframe1').contents().find('[src*="myimg"]')
but I am getting error as below
Uncaught Error: Syntax error, unrecognized expression:
[src*="myimg"])
at Function.Sizzle.error (jquery-1.8.2.js:4679)
at tokenize (jquery-1.8.2.js:4739)
at select (jquery-1.8.2.js:5099)
at select (jquery-1.8.2.js:5276)
at Function.Sizzle [as find] (jquery-1.8.2.js:3941)
at init.find (jquery-1.8.2.js:5372)
at <anonymous>:1:36
What's wrong here?
Update
alert($('#if').contents().find('[src*="ss"]').next().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id='if'>
<img src='sss.jpg' />
<div>
scdscd
</div>
</iframe>
Simply do:
var x = $("img[src$='myimg.jpg']");
alert(x.attr("src"));
Use contains selector, and as Enfyve mentioned in comments remove extra ).
images = $('#iframe1').contents().find('[src~="myimg"]')
You are wrong about using an iframe.
The iframe must use the src attribute and use it to load the contents of other pages. An iframe does not need to include its child elements directly in its tag.
You can try this.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id='if' src="1.html">
</iframe>
//1.html
...
<img src='sss.jpg' />
<div>
scdscd
</div>
and you can try as following.
alert($('#iframe1').contents().find('[src*="ss"]').next().html());
Selector is correctly working. You can see working jsbin here.
Incorrect usage of iframe is causing issue for you.
If you want add contents to iframe either you have to specify URL using src attribute or HTML string using srcdoc attribute.
The srcdoc attribute specifies the HTML content of the page to show in the inline frame.
Reference iframe srdoc
make sure that your iframe src is targeting the same domain as your main page. Otherwise you are not allowed to access iframe content. This is called XSS (Cross Site Scripting) and it's prevented by major browsers.
If your iframe source is on the same domain and you still can't access it's content make sure to set a setTimeout waiting for iframe content to be loaded because iframe content start loading after the main page is loaded.

Javascript fails because of double inverted comma in a test

I have some text saved in my database in HTML format, This text was saved into datatbase from a email.
Sometimes emails have single or double opening inverted commas but no closing inverted commans.
Becuase of this other scripts on the page stop to work.
How can i prevent this html code which i am reading from database to not affect my page style or scripts.
You can consider my application to be simple email reading application.
Any email that i read from database even if it has improper/buggy html, i don't want it to break my code.
Please let me know how i can fix this issues
I am working on following
- Laravel
- Bootstrap
Always escape the data that you receive from the client or you will become a victim of XSS (Cross Site Scripting).
That said if you really want to do it then there are two ways so that the content of the email doesn't affect your code.
IFrame
Shadow DOM
Both of these have a separate context than the parent page so they will not interfere with your code unless the code inside them manually tries to access parent.
Following is the sample for both. Same on JSFiddle
<html>
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="iframeParent">
</div>
<div id="shadowParent">
</div>
<script>
var emailContent = "<h1>helloworld</h1>";
var iframeContainer = $("#iframeParent");
$('<iframe/>').appendTo(iframeContainer).on("load", function () {
$(this).contents().find("body").html(emailContent);//firefox
}).contents().find("body").html(emailContent);//chrome
var shadowContainer = $("#shadowParent");
alert(shadowDom);
var shadowDom = shadowContainer.get(0).createShadowRoot();
shadowDom.innerHTML = emailContent;
</script>
</body>
</html>
Note: Shadom DOM is probably not the best solution as it's not enabled by default on the firefox. See this link

how to get a class value from an iframe parent page

I have two applications one is already built and the other one is my own I can't do any modification in the first one and it uses iframes and in that frame I can put my application but I will need the name of the connected users which the only option is to get it from the source code using javascript the problem is that user name inside a css class not id
if you have any ideas how can I get it please help thanks to you all
<div class="Entete_User">
<div class="Entete_UserName">USER NAME <br> USER CITY</div>
</div>
<div class="body">
<iframe id="myiframe" frameborder="0" allowTransparency="allowTransparency" src="MYPAGE.aspx"></iframe>
</div>
</form>
To get the content of the element in the parent window from inside the iFrame :
window.parent.document.getElementsByClassName('Entete_UserName')[0].innerHTML;
Try this but make sure Iframe and your origin page in same domain as iframe does not support cross domain
JavaScript
window.parent.document.getElementById('parentElement')[0].innerHTML;;
Jquery
$('#parentElement', window.parent.document);
this is for outside the iframe trying to see whats inside..
document.getElementById("myiframe").contentWindow.document.getElementById()
but you have to be on the same domain

Categories