Search code examples
javascriptsame-origin-policy

Javascript: can I make two websites interact via javascript?


This is a simplified example: I use two online dictionaries, but each one has only a set of features I need. However it's a pain to click through both and type in the words in two places. I would like to write my own javascript webpage, that loads elements from the two sites, i.e. the input field for the word, and then displays the results from the two sites on the same page.

My script would need to read elements from one page, and use that data to manipulate the other page.

When I tried researching this I encountered the same origin policy, but apparently chrome there's a workaround. My question is is this possible via browsers and javascript or would I have to look at a completely different technology like Python and webscraping.


Solution

  • If it's just to consult the two websites for the same term at the same time, you could have your webpage with two iframes and set their src attributes like the following:

    $("#search").click(function () {
        var term = $("#term").val();
        $("#dictionary").attr("src", "http://www.dictionary.com/browse/" + term);
        $("#free").attr("src", "https://www.thefreedictionary.com/" + term);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input id="term" type="text" placeholder="search dictionaries">
    <input id="search" type="button" value="Search"><br>
    <iframe id="dictionary" src="about:blank" style="width:45vw;height:500px;"></iframe>
    <iframe id="free" src="about:blank" style="width:45vw;height:500px"></iframe>

    The URL of the website is their API. Just look at the address bar after you've done a search on their site to find out how to construct it yourself.

    Bonus

    I myself use different websites like this, but via custom commands to automatically open multiple tabs in the browser (which you can also do via Javascript).

    I use commands on linux like the following (declared in .bashrc):

    function d {
        firefox "http://www.dictionary.com/browse/$1+$2+$3+$4+$5"&exit
    }
    

    which means, without firefox even being open, I can open a terminal (with a keyboard shortcut) and type d test to launch firefox and search a dictionary for test. If firefox is already running it'll be brought to the foreground and the website will open in a new tab.

    In windows you can add batch files (*.bat) or command files (*.cmd) to do the same thing. In c:\windows you can create a file called d.cmd with:

    start "" "http://www.dictionary.com/browse/%1+%2+%3+%4+%5"
    

    then use the keyboard shortcut Win+R to open the run dialog and type d test.

    The run dialog used to be in the Start Menu, they've probably hidden it on your version of windows.