Slava
Slava

Reputation: 6650

How to access another tab in Chrome in javascript?

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

Upvotes: 3

Views: 6170

Answers (2)

spl1nter
spl1nter

Reputation: 9

Use Window.postMessage

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

Im sure it will helpfull

Upvotes: -1

T.J. Crowder
T.J. Crowder

Reputation: 1074989

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.

Upvotes: 2

Related Questions