简体   繁体   中英

Javascript - redirect to another website and call Javascript function after that page loads

Scenario: you have a link to another website (say yahoo.com) on your webpage, and a user clicks the link.

Can you have Javascript functions be called and HTML/CSS be loaded on the page even though it's on a totally different domain? Like, rendering some sort of sidebar on Yahoo?

If not (which I assume is the case), are there other ways of doing this?

The short answer is NO , you cannot.

You can of course do workarounds, like Blender suggest in his comment, embedding an iframe with the site, but due to the same-origin policy you will not be allowed any access to the content loaded within the iframe if it originates from another domain. That goes for both CSS and JavaScript, so you will not be able to modify the content in any way.

Tha said, you could perhaps load the content in an iframe and have a "sidebar" on your own page, along side the iframe. When you click on any link in your "sidebar" you load that reference within the iframe, creating a "feel" that the sidebar relates to the content of the iframe. It is in no way a great solution, but it is the closest I can think of at the moment.

Update

Extended the example provided by @kieran in his comment, with a few links, so here is a working example of what I described above.

Your DOM would look similar to this:

<div class="sidebar">
    <a href="http://images.yahoo.com/" target="container">Yahoo images</a><br/>
    <a href="http://news.yahoo.com/" target="container">Yahoo news</a>
</div>
<iframe name="container" class="site-container" src="http://www.yahoo.com/" />

And some CSS that you could modify to fit your needs:

.sidebar {
    width: 150px;
    float: left;
    background-color: #ccc;
    border-right: 1px solid #888;
}

.site-container {
    border: 0;
}

.sidebar,
.site-container {
    height: 300px;
}

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