简体   繁体   中英

Get text from an element inside an iframe

Well I wanted to get the text from a tag element inside an iframe, what I mean is that I would like to click any element inside said iframe and be able to retrieve the text of said tag back to the parent window just like this code does with my current page:

$(document).click(function(event) {
    var text = $(event.target).text();
});

PS: The website contained in the iFrame is not under my control basically I want to web scrape the website but was trying to create a tool to ease the process

So in order to communicate between the iframe and parent window, either the content of the iframe has to have been generated by the JavaScript (not sure if it applies if it's an iframe of another file on the same server as well...) Or you have to otherwise have access to the source code of the iframe page, to implement the postMessage API to send data to and from the main page

For example, somewhere in your iframe source code, like on the click of an element, you can call postMessage to send a message to the main frame

myButton.onclick= ()=>{
    parent.postMessage({message:"you clicked something"},"*")
}

Then in the main file you listen for new messages

onmessage = e=> 
    console.log(e.data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM