How to get url as string from JSON when sending messages in Firefox or Chrome?

113 views Asked by At

For a Firefox (or Chrome) addon, I want a content script to send messages containing text IDs and urls to a background script. I want the background script to output the IDs and urls as simple strings using console.log(), but the urls are coming out with quotes and hyperlinks.

How can I get the urls to be output as simple strings?

Here's, for example, what I am aiming for console.log() to output:

The url is: h!!ps://upload.wikimedia.org/wikipedia/commons/c/c6/Sirius.jpg

Content script:

// content-script.js

var identifier = "Sirius";
var link = "https://upload.wikimedia.org/wikipedia/commons/c/c6/Sirius.jpg";
var strippedLink = "upload.wikimedia.org/wikipedia/commons/c/c6/Sirius.jpg";

var myPort = browser.runtime.connect({name:"port-from-cs"});
myPort.postMessage({theId: identifier, theUrl: link, theStripped: strippedLink});

Background script:

// background-script.js

var portFromCS;

function connected(p) {
  portFromCS = p;
  portFromCS.onMessage.addListener(function(m) {
    var ident = m.theId; 
    var url = m.theUrl;
    var altUrl = m.theStripped;

    // (A)
    console.log("(A) The ID is: " + ident);

    // (B)
    console.log("(B) The stripped url is: " + altUrl);

    // (C)
    console.log("(C) The url is: " + url);

    // (D)
    console.log("(D) The url is: ");
    console.log(url);
  });
};


browser.runtime.onConnect.addListener(connected);

(A) outputs the format I am aiming for (except A doesn't have any urls).

(B) is also ok, except that I would want to be able to include the protocol (http or https) in the original string that is sent in the message.

(C), and (D) result in hyperlinks and quotes.

edit:

What I want is

The url is: https://upload.wikimedia.org/wikipedia/commons/c/c6/Sirius.jpg

copy/paste from console follows (references to code lines removed):

(A) The ID is: Sirius

(B) The stripped url is: upload.wikimedia.org/wikipedia/commons/c/c6/Sirius.jpg

"(C) The url is: https://upload.wikimedia.org/wikipedia/commons/c/c6/Sirius.jpg"

(D) The url is:
"https://upload.wikimedia.org/wikipedia/commons/c/c6/Sirius.jpg"

0

There are 0 answers