简体   繁体   English

Javascript-重定向到另一个网站,并在该页面加载后调用Javascript函数

[英]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. 场景:您在网页上有一个指向另一个网站(例如yahoo.com)的链接,并且用户单击该链接。

Can you have Javascript functions be called and HTML/CSS be loaded on the page even though it's on a totally different domain? 即使页面位于完全不同的域中,也可以调用Javascript函数并在页面上加载HTML / CSS吗? Like, rendering some sort of sidebar on Yahoo? 例如,在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. 当然,您可以采取解决方法,例如Blender在他的评论中建议,将iframe嵌入网站,但是由于同源政策 ,如果iframe中加载的内容来自另一个域,则您将无法对其进行任何访问。 That goes for both CSS and JavaScript, so you will not be able to modify the content in any way. CSS和JavaScript都适用,因此您将无法以任何方式修改内容。

Tha said, you could perhaps load the content in an iframe and have a "sidebar" on your own page, along side the iframe. 他说,您也许可以将内容加载到iframe中,并在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. 当您单击“侧边栏”中的任何链接时,您会在iframe中加载该引用,从而创建一个“感觉”,即侧边栏与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. 扩展了@kieran在其评论中提供的示例,并提供了一些链接,因此这里是我上面所描述的一个有效示例

Your DOM would look similar to this: 您的DOM看起来类似于:

<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: 以及一些可以修改以适合您的需求的CSS:

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

.site-container {
    border: 0;
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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