How to access another tab in Chrome in javascript?

时间:2017-08-04 12:33:35

标签: javascript google-chrome

Basically, when I run this script in Chrome console, I want to get current url, open a new tab, and set it as a value of a textbox.

javascript:(function(){
    var url=location.href;
    var newtab=window.open('http://www.theyoump3.com/');
    newtab.document.getElementsByName('url')[0].value=url;
})();

When I run the command I get exception in console:

Uncaught DOMException: Blocked a frame with origin "https://www.youtube.com" from accessing a cross-origin frame.

Its understood, the CORS problem. Is there a workaround? Passing a url parameter is not supported by that site.

Same problem occurs when trying this via iframe

var f=document.createElement('iframe');
f.src='https://www.youtube.com/watch?v=4J2zo7ArHnw';
f.style="position:absolute;width:400px;height:400px;z-index:99999;border:2px solid black";
document.body.appendChild(f);

of course it will work then src point to the same origin

2 个答案:

答案 0 :(得分:1)

If your starting point isn't the same origin as http://www.theyoump3.com/, you won't be able to do this because the JavaScript code you run in the console runs in the context and origin of the page the console is attached to.

If you are doing it from a page on that origin, you just have to wait for the load event:

javascript:(function(){
    var url=location.href;
    var newtab=window.open('http://www.theyoump3.com/');
    newtab.addEventListener("load", function() {
        newtab.document.getElementsByName('url')[0].value=url;
    });
})();

But again: Only if you're starting out on that origin, which I'm guessing you aren't.

答案 1 :(得分:-1)

使用Window.postMessage

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

我相信它会有所帮助

相关问题