0

I'm send XMLHttpRequest and want to send it only to real domains, which are not null and are not Chrome's internal chrome: domains.

Until now i fail on this - my XMLHttpRequest is sending under any circumstances - but in case of currentDomaon == 0 or currentProtocoll == "chrome:" it comes empty.

What i'm doing wrong? How should i adapt the code to get the goal?

var currentDomain = "";
var currentProtocol ="";
const processingTabId = {};

function run(tab) {
    if (processingTabId[tab.id]) return;
    processingTabId[tab.id] = true;

    let newUrl = new URL(tab.pendingUrl || tab.url)
    currentDomain = newUrl.hostname;
    currentProtocol = newUrl.protocol;

        var xhr = new XMLHttpRequest();
        var protocol = "https://";
        var middle = ".myservice/"
        var end = "/action/data/";

        xhr.open("GET", protocol + middle + currentDomain + end, true);

        xhr.responseType = 'document';

if (currentDomain !== null) && (currentProtocol !== "chrome:") {
xhr.send();
        }       
}
Evgeniy
  • 2,337
  • 2
  • 28
  • 68
  • Why would you be trying to send a request to any of those domains in the first place? In what context will this be used, do you not control where requests are sent? – rhys_stubbs Mar 15 '20 at 22:04
  • if (currentDomain && currentProtocol ==="https:") – mplungjan Mar 15 '20 at 22:11
  • @mplungjan `currentDomain` could be anything - it is domain with subdomain without protocol, `currentProtocol` could be `http:` too – Evgeniy Mar 15 '20 at 22:14
  • 1
    if (currentDomain) would test null, undefined and empty Then use `if (currentDomain && currentProtoco.indexOf("http") ===0)` – mplungjan Mar 15 '20 at 22:17
  • @mplungjan then it should be something like `if (currentDomain && currentProtocol === ("https:" || "http:"))` - correct? – Evgeniy Mar 15 '20 at 22:18
  • It is extremely unlikely you will find any protocol like httpblala or something. But yeah, your JS is not valid. Try `if (currentDomain && ["http:","https"].includes(currentProtocol))` – mplungjan Mar 15 '20 at 22:22

1 Answers1

-2

You could use a Regular Expression to determine if a string is a valid URL starting with HTTP/HTTPS.

For example:

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

See this Stack Overflow post.

rhys_stubbs
  • 538
  • 6
  • 16